Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private scope and inheritance in java

Tags:

java

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 ?

like image 481
user1150082 Avatar asked Sep 06 '26 09:09

user1150082


2 Answers

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.

like image 150
Bathsheba Avatar answered Sep 07 '26 23:09

Bathsheba


Field 'a' is inherited. It is not directly accessible from class B. Only class A can access field a.

like image 43
Mateusz Balbus Avatar answered Sep 07 '26 22:09

Mateusz Balbus