Java : Using parent class method to access child class variable

Posted by Jayant on Stack Overflow See other posts from Stack Overflow or by Jayant
Published on 2012-07-04T01:36:07Z Indexed on 2012/07/04 3:16 UTC
Read the original article Hit count: 101

Filed under:
|
|

I have the following scenario :

public class A {

    private int x = 5;

    public void print()
    {
        System.out.println(x);
    }
}


public class B extends A {

    private int x = 10;

    /*public void print()
    {
        System.out.println(x);      
    }*/

    public static void main(String[] args) {
        B b = new B();
        b.print();
    }

}

On executing the code, the output is : 5.

How to access the child class(B's) variable(x) via the parent class method?

Could this be done without overriding the print() method (i.e. uncommenting it in B)?

[This is important because on overriding we will have to rewrite the whole code for the print() method again]

© Stack Overflow or respective owner

Related posts about java

Related posts about oop