Consider this simple java code :
class A {
private int a = 10;
public void print() {
System.out.println(this.getClass().getName() + " " + a);
}
}
public class B extends A {
public void p1() {
print();
}
public static void main(String... args) {
B b = new B();
b.p1();
}
}
If you will run the code , the value that gets printed is B 10 . My question is if "a" is not inherited when we use "private" modifier but the method is , then there is method print() in class B now but "a" is not part of the class since it is private, so how is it that the compiler doesn't throw error when we try to access it by saying scope of "a " is private ?
print in class A is reachable in class B as it's public and class B is a child of class A.
But print in class A can see all the fields in class A since it's a method of that class. So that function can see a, and hence compilation passes.
Field 'a' is inherited. It is not directly accessible from class B. Only class A can access field a.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With