Java: accessing subclass variables using parent methods
I have the following conditions:
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(); } }
When executing the code, the output is: 5
How to access the variable (x) of subclass (b) through the parent method?
Can this be done without overriding the print () method (that is, uncomment in B)?
[this is important because when rewriting, we will have to rewrite the entire code of the print () method.)
EDITED
Further clarification:
>The motivation for the problem is to use the values of subclass private variables from parent methods This does not require changing the value of the private variable of the parent class to achieve the desired results. > However, the answers posted here have given me the answers I expected. I have posted below
(thanks for all your time and help)
Solution
class A {
class A { private int x = 5; protected int getX() { return x; } protected void setX(int x) { this.x = x; } public void print() { // getX() is used such that // subclass overriding getX() can be reflected in print(); System.out.println(getX()); } } class B extends A { public B() { // setX(10); // perhaps set the X to 10 in constructor or in main } public static void main(String[] args) { B b = new B(); b.setX(10); b.print(); } }
EDITED
The following is a general answer to using abstract classes and methods to solve similar situations:
abstract class SuperA { protected abstract Object getObj(); public void print() { System.out.println(getObj()); } } class A extends SuperA { @Override protected Object getObj() { // Your implementation return null; // return what you want } } class B extends A { @Override protected Object getObj() { // Your implementation return null; // return what you want } public static void main(String[] args) { B b = new B(); b.print(); } }