Access Control in Inheritance in Java
In Java, access control in inheritance determines how members (fields, methods,
constructors) of a superclass can be accessed in a subclass. Java provides four levels of access
control:
Subclass (Different
Modifier Same Class Same Package Everywhere
Package)
private ✅ ❌ ❌ ❌
default (no
✅ ✅ ❌ ❌
modifier)
protected ✅ ✅ ✅ ❌
public ✅ ✅ ✅ ✅
1. private Access Modifier
Members declared private in the superclass are not accessible in the subclass.
These members are only accessible within the same class.
class Parent {
private int privateVar = 10;
}
class Child extends Parent {
void display() {
// [Link](privateVar); // ERROR: privateVar is not accessible
}
}
2. Default (No Modifier) Access
Members without an access modifier are only accessible within the same package.
If a subclass is in a different package, it cannot access the default members.
package package1;
class Parent {
int defaultVar = 20; // Default access
}
package package2;
import [Link];
class Child extends Parent {
void display() {
// [Link](defaultVar); // ERROR: defaultVar is not accessible
}
}
3. protected Access Modifier
Members declared protected can be accessed:
o Within the same package (like default access).
o By subclasses in any package (via inheritance).
package package1;
public class Parent {
protected int protectedVar = 30;
}
package package2;
import [Link];
class Child extends Parent {
void display() {
[Link](protectedVar); // ✅ Accessible because it's protected
}
}
4. public Access Modifier
public members are accessible from anywhere (within and outside packages).
package package1;
public class Parent {
public int publicVar = 40;
}
package package2;
import [Link];
class Child extends Parent {
void display() {
[Link](publicVar); // ✅ Accessible from anywhere
}
}
Accessing Protected Members Using Superclass Reference
Even though protected members can be accessed in subclasses, they cannot be accessed
through a superclass reference from another package.
package package1;
public class Parent {
protected int protectedVar = 50;
}
package package2;
import [Link];
class Test {
public static void main(String[] args) {
Parent obj = new Parent();
// [Link]([Link]); // ERROR: Not accessible through
Parent reference
}
}
Key Takeaways
private → Not inherited, only accessible in the same class.
default (no modifier) → Accessible only within the same package.
protected → Accessible within the same package and in subclasses (even
in different packages).
public → Accessible everywhere.