i have a few sub classes with unique static vars in this case called 'x'. All of those sub classes are using the static var the same way, so I want to reduce code duplication and put the functionality in the super class. In this case the method 'getX' in the super class. From here I want to return the value of x. Right now I'm facing the issue that it uses the x value of the super class and not the value of the child class. How can I access the x value of the sub class from the super class?
public class Playground {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
Child1 child1 = new Child1();
System.out.println("Parent.x " + parent.x);
System.out.println("child.x " + child.x);
System.out.println("child.x " + child1.x);
System.out.println("get x: " + parent.getX());
System.out.println("get x: " + child.getX());
}
}
class Parent {
static String x = "static of parent";
String y = "instance of parent";
String getX() {
return x;
}
}
class Child extends Parent {
static String x = "static of child";
String y = "instance of child";
}
class Child1 extends Parent {
static String x = "static of child1";
String y = "instance of child";
}
This code prints out:
Parent.x static of parent
child.x static of child
child.x static of child1
get x: static of parent
get x: static of parent
<-- here should be static of child
Hope someone can help me.
Cheers
Add the getX method in the child class. The parent getX method points to the static variable of the parent class.