Question

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 in parent class live in the Child object, there are two fields that shares the same name (a) and getter and setter in the Child object so how java resolve this getter and setter method for private field in parent class ?

Was it helpful?

Solution

The getA() method is defined in the superclass only, and can only access members of the superclass. It cannot know about the a of the subclass, so the a of the subclass cannot shadow it.

Whether the member a of the subclass is private or public is not relevant. You will see the same behavior if you declare a to be private in the child class.

Update: Here is an attempt to answer the more general question: How are members which are defined in both parent and subclasses resolved?

Consider the following extension of the OP's example:

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());        
    }
}

Here, we see the output 10 and 20, which implies that class C's getA() method is reading class B's version of a.

Now let us see what happens if we make B's version of A private.

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

If we try to compile, we will get a compiler error:

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

The experiment above seems to suggest that each class will attempt to resolve a by looking at either itself or go up the class hierarchy until it finds the first a. If that a is visible to it (meaning public or protected), then it will return it. If that a is not visible, then it will simply not compile.

OTHER TIPS

When you call getA(), you are calling A's method that will return A's variable's value.

If you overwrite getA() in class B, the output will be 20, because it will be getting variable "a" in B's context.

If you call setA, from class B's object, it will reflect on A's attributes only. Even you have set B's variable directly (because of public), the result will still be 10.

That means: you shouldn't set/get variables directly. Use the methods instead. You should set a variable the way you did if you want a default value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top