【发布时间】:2011-06-29 19:16:56
【问题描述】:
我有两个类 A 和 B 如下
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;
}
}
我的主要是
public class Main {
public static void main(String[] args) {
B test = new B();
test.setX(9);
System.out.println(test.getX());
}
}
输出为 0。我希望它为 9。我意识到在这个简单的示例中,我可以在 B 中的方法中写 x = 9,但如果它是一个更复杂的方法,我不想重写所有已经在我的超类方法中编写的代码,那么我将如何实现呢?
编辑:在子类 B 中,我故意调用我的 int 变量 x 来隐藏超类变量 x。假设超类中的 setX 方法在最终设置 x 之前做了很多其他的事情。我希望它设置子类的 x 。这可能吗?这是一个琐碎的例子。在我的实际问题中,它要复杂得多。
编辑:实际问题是这样的。我有一个名为ColorBinaryTree 的类,它是BinaryTree 的子类。唯一的区别是ColorBinaryTree 类有一个颜色字段,所以我可以实现一个红黑树。 BinaryTree 类对 parent、left 和 right 的引用,它们都是 BinaryTree 对象。 ColorBinaryTree 类具有相同的引用,但它们是 ColorBinaryTree 对象而不是 BinaryTree 对象。我有一堆操纵树的方法。一个例子如下
public BinaryTree<E> root() {
if (parent == null) return this;
else return parent.root();
}
在我的子类中,我需要重写它,以便我可以做协变返回类型并返回一个 ColorBinaryTree 对象。但是,如果我可以在我的子类方法中调用超类方法,那就太好了。但似乎如果我调用超类方法,它会查看超类的父字段。我希望它查看子类的父字段。
【问题讨论】:
标签: java inheritance field hidden