I have two classes A and B as below
public class A {
Number x;
public A (){
x = 10;
}
public void setX(Number x){
//do a bunch of super complicated and lengthy stuff
// afterwards set x
this.x = x;
}
}
public class B extends A{
int x;
public B(){
super();
}
public void setX(int x){
super.setX(x);
}
public int getX(){
return x;
}
}
and my Main is
public class Main {
public static void main(String[] args) {
B test = new B();
test.setX(9);
System.out.println(test.getX());
}
}
The output is 0. I want it to be 9. I realize that in this trivial example I could just write x = 9 in my method in B, but if it were a more complicated method where I didn’t want to rewrite all the code that was already written in my superclass method then how would I make that happen?
EDIT: in subclass B I am purposely calling my int variable x to hide the superclass variable x. Pretend the setX method in the superclass does a ton of other stuff before finally setting x. I want it to set the x of the subclass instead. is this possible? This is a trivialized example. In my actual problem it’s much more complicated.
EDIT: actual problem is this. I have a class called ColorBinaryTree which is a subclass of BinaryTree. the only difference is the ColorBinaryTree class has a field for color so I can implement a red-black tree. The BinaryTree class references to parent, left, and right which are all BinaryTree objects. The ColorBinaryTree class has the same references but they are ColorBinaryTree objects instead of BinaryTree objects. I have a bunch of methods which manipulate the tree. One example would be the following
public BinaryTree<E> root() {
if (parent == null) return this;
else return parent.root();
}
In my subclass I need to override this so I can do covariant return type and return a ColorBinaryTree object. But it would be nice if i could call the superclass method inside my subclass method. But it seems that if I call the superclass method it looks at the superclass’s parentfield. I want it to look at the subclass’s parent field.
As you use generics, you use Java 5. What about overriding the methods with a more specific return type:
Or may use a more sophisticated generic solution: