Bird
Raised Fist0
Javaprogramming~10 mins

Protected access modifier in Java - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Protected access modifier
Class A defines protected member
↓
Class B extends Class A?
No→Cannot access protected member
Yes↓
Class B accesses protected member
↓
Access allowed within same package or subclass
Protected members are accessible within the same package and by subclasses even if they are in different packages.
Execution Sample
Java
class A {
  protected int num = 10;
}

class B extends A {
  int getNum() { return num; }
}
Class B inherits from A and accesses the protected member num.
Execution Table
StepActionClass ContextMember AccessResult
1Create instance of AAnumnum = 10
2Create instance of BB extends Ainherits numnum = 10
3Call getNum() on B instanceBaccess protected numreturns 10
4Try access num from unrelated classUnrelatedaccess protected numAccess denied
💡 Access denied outside subclass or package; protected allows subclass and package access only
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
numundefined10 (in A instance)10 (in B instance)10 (returned by getNum)10
Key Moments - 2 Insights
Why can class B access num but an unrelated class cannot?
Because num is protected, it is accessible in subclasses like B (see execution_table step 3), but not in unrelated classes (step 4).
Does protected mean public access?
No, protected is more restrictive: only subclasses and classes in the same package can access (see concept_flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what value does getNum() return at step 3?
AAccess denied error
B0
C10
DUndefined
💡 Hint
Check execution_table row with Step 3 for the returned value.
At which step is access to num denied?
AStep 4
BStep 2
CStep 1
DStep 3
💡 Hint
Look for 'Access denied' in the Result column of execution_table.
If num was private instead of protected, which step would fail?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Private members are not accessible in subclasses; see step 3 where subclass accesses num.
Concept Snapshot
protected member:
- accessible in same package
- accessible in subclasses (even in different packages)
- not accessible by unrelated classes
syntax: protected type name;
used for controlled access in inheritance
Full Transcript
The protected access modifier in Java allows a class member to be accessed within its own package and by subclasses even if they are in different packages. In the example, class A defines a protected integer num. Class B extends A and can access num directly. When B's method getNum() returns num, it returns 10. However, an unrelated class cannot access num because it is protected, not public. This shows protected is more restrictive than public but more open than private. Protected is useful to share members with subclasses and package classes while hiding them from others.

Practice

(1/5)
1. Which statement best describes the protected access modifier in Java?
easy
A. It allows access only within the same class.
B. It allows access only within the same package, not subclasses outside.
C. It allows access from any class anywhere.
D. It allows access within the same package and to subclasses outside the package.

Solution

  1. Step 1: Understand protected access scope

    The protected modifier allows access to members within the same package and also to subclasses even if they are in different packages.
  2. Step 2: Compare with other access levels

    Private restricts access to the same class only, public allows everywhere, and default (package-private) allows only within the same package but not subclasses outside.
  3. Final Answer:

    It allows access within the same package and to subclasses outside the package. -> Option D
  4. Quick Check:

    Protected = same package + subclasses outside [OK]
Hint: Protected means package + subclass access [OK]
Common Mistakes:
  • Confusing protected with private
  • Thinking protected is public
  • Assuming protected restricts subclasses outside package
2. Which of the following is the correct way to declare a protected method in Java?
easy
A. private protected void myMethod() {}
B. public protected void myMethod() {}
C. protected void myMethod() {}
D. void protected myMethod() {}

Solution

  1. Step 1: Recall Java access modifier syntax

    In Java, access modifiers come before the return type and method name. Only one access modifier is allowed per method declaration.
  2. Step 2: Identify valid syntax

    protected void myMethod() {} correctly uses protected followed by the return type void and method name. Other options combine modifiers incorrectly or place them in wrong order.
  3. Final Answer:

    protected void myMethod() {} -> Option C
  4. Quick Check:

    Single access modifier before return type [OK]
Hint: Use only one access modifier before return type [OK]
Common Mistakes:
  • Combining multiple access modifiers
  • Placing modifiers after return type
  • Using invalid modifier combinations
3. Consider the following code in two packages:
package pkg1;
public class Parent {
    protected int value = 10;
}

package pkg2;
import pkg1.Parent;
public class Child extends Parent {
    public int getValue() {
        return value;
    }
}

public class Test {
    public static void main(String[] args) {
        Child c = new Child();
        System.out.println(c.getValue());
    }
}

What is the output when running Test.main?
medium
A. 0
B. 10
C. Compilation error due to access
D. Runtime error

Solution

  1. Step 1: Check access of protected member in subclass outside package

    The value field is protected in Parent. The Child class extends Parent and accesses value in getValue(). This is allowed because protected permits subclass access even outside the package.
  2. Step 2: Trace the output of getValue()

    The method returns value which is initialized to 10. So, printing c.getValue() outputs 10.
  3. Final Answer:

    10 -> Option B
  4. Quick Check:

    Protected allows subclass access outside package [OK]
Hint: Protected allows subclass access outside package [OK]
Common Mistakes:
  • Thinking protected blocks subclass outside package
  • Expecting compilation error
  • Confusing default access with protected
4. Identify the error in the following code:
package pkg1;
public class Parent {
    protected int data = 5;
}

package pkg2;
import pkg1.Parent;
public class Other {
    public void printData() {
        Parent p = new Parent();
        System.out.println(p.data);
    }
}
medium
A. Cannot access protected member from non-subclass in different package
B. No error, code runs fine
C. Syntax error in import statement
D. Cannot create instance of Parent class

Solution

  1. Step 1: Analyze access of protected member from non-subclass outside package

    The class Other is not a subclass of Parent and is in a different package. Accessing p.data is not allowed because protected members are accessible only within the same package or subclasses outside the package.
  2. Step 2: Identify the error type

    This causes a compilation error due to illegal access of a protected member from a non-subclass outside the package.
  3. Final Answer:

    Cannot access protected member from non-subclass in different package -> Option A
  4. Quick Check:

    Protected blocks non-subclass outside package [OK]
Hint: Protected blocks non-subclass outside package [OK]
Common Mistakes:
  • Assuming protected allows all package access
  • Confusing subclass and non-subclass access
  • Ignoring package differences
5. You have a class Animal in package zoo with a protected method makeSound(). You want to allow only subclasses in any package to use makeSound(), but prevent other classes in the same package from calling it. How can you achieve this?
hard
A. Declare makeSound() as protected and move other classes out of the package.
B. Declare makeSound() as protected and make other classes subclasses of Animal.
C. Declare makeSound() as private and provide a public wrapper method.
D. Declare makeSound() as protected and keep other classes in the same package.

Solution

  1. Step 1: Understand protected access within package and subclasses

    Protected members are accessible to all classes in the same package and to subclasses outside the package. So, classes in the same package can call makeSound() even if they are not subclasses.
  2. Step 2: Restrict access to only subclasses

    To prevent other classes in the same package from accessing makeSound(), you must move those classes to a different package. Then only subclasses (in any package) can access the protected method.
  3. Final Answer:

    Declare makeSound() as protected and move other classes out of the package. -> Option A
  4. Quick Check:

    Protected allows package + subclass; move non-subclass classes out [OK]
Hint: Protected allows package access; move classes to restrict [OK]
Common Mistakes:
  • Thinking protected blocks same-package classes
  • Making other classes subclasses to restrict access
  • Using private which blocks subclasses
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard