0
0
Javaprogramming~15 mins

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

Choose your learning style8 modes available
flowchartConcept Flow - Protected access modifier
Class A defines protected member
Class B extends Class A?
NoCannot 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.
code_blocksExecution 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.
data_tableExecution 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
search_insightsVariable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
numundefined10 (in A instance)10 (in B instance)10 (returned by getNum)10
keyKey Moments - 2 Insights
Why can class B access num but an unrelated class cannot?
Does protected mean public access?
psychologyVisual 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
photo_cameraConcept 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
contractFull 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.