0

I read that in Java private members are not inherited. But I wrote this piece of code where j is a private member of superclass A, and it seems subclass B inherited it completely fine.

class A{
    int i;
    private int j;
    void setI(int i){
        this.i = i;
    }
    void setJ(int j){
        this.j = j;
    }
    int getI(){
        return i;
    }
    int getJ(){
        return j;
    }
}
class B extends A{
    int k;
    void setK(int k){
        this.k = k;
    }
    int getK(){
        return k;
    }
}
public class Main {
    public static void main(String args[]) {
        B b = new B();
        b.setI(1);
        b.setJ(2);
        b.setK(3);
        System.out.println(b.getI() + " " + b.getJ() + " " + b.getK());
    }
}

Output:

1 2 3

Can anyone clarify what actually happening?

  • 2
    Note: You are not directly accessing the value of `j` for example, instead you are in-directly calling the `setJ` method in the super/inherited class which does have valid access. You will get an error if you use `j = 2;` in the `B` class, or `b.j = 2;` in the main class. – sorifiend Jun 21 '21 at 05:38

0 Answers0