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]
EDITED
More Clarification :-
- The motive of the question is to use the value of a child class private variable from its parent class method. This doesn't require changing the value of the parent class private variable in order to achieve the desired result.
- The answers posted here, though, led me to my desired answer, which I have posted below.
(Thanks all for your time and help )
x, do you intend forxto be different from A'sx, or should they be the same?xinAis to be 5, the one inBis to be 10. He wantsB.print()to output 10, because he's not happy with an output of 5. Thus he expects them to be different.xisn't overridden during creation ofB.xisn't updated whenBis created, because default values are only evaluated once.