Explain this result.

class A {
    private int a = 10;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;       
    }    
}

class B extends A {
    public int a = 20;
}

public class Demo {
    public static void main(String args[]) {
        B a = new B();
        System.out.println(a.getA());        
    }
}

output: 10
Since all the fields of the parent class live in the Child object, are there two fields that have the same name (a) and getter and setter in the Child object, since java allows this getter and setter method for the private field in the parent class?

+4
source share
2 answers

The method is getA()defined only in the superclass and can only access members of the superclass. He cannot know about the asubclass, therefore the asubclass cannot put out his.

a , . , a .

: : , , ?

OP:

class A {
    public int a = 10;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;       
    }    
}

class B extends A {
    public int a = 20;
}
class C extends B {
    public int getA() {
        return a;
    }
}

public class Demo {
    public static void main(String args[]) {
        B a = new B();
        System.out.println(a.getA());        

        C c = new C();
        System.out.println(c.getA());        
    }
}

10 20, , C getA() B a.

, , B a .

class B extends A {
    private int a = 20;
}

, :

Demo.java:18: error: a has private access in B

, -, , a, , , a. a ( public protected), . a , .

+6

getA(), , .

getA() B, 20, "a" B.

setA, B, A. B (- ), 10.

: / . . , , .

0

Source: https://habr.com/ru/post/1533029/


All Articles