java java类A扩展类B,方法覆盖
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10646199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java class A extends class B, and method override
提问by xiaofan2406
public class A {
protected ClassX a;
public void foo() {
operations on a;
}
}
public class B extends A {
private ClassY b; // ClassY extends ClassX
@Override
public void foo() {
//wanna the exact same operation as A.foo(), but on b;
}
}
Sorry for such a not clear title. My question is: in class B, when I call foo(), and I want the exact same operation as class A have on a. How do I achive that and without duplicate the same code from A? If i leave out foo() in class B, would it work? Or whats happening when I call super.foo() in foo();
对不起,这样一个不清楚的标题。我的问题是:在 B 类中,当我调用 foo() 时,我想要与 A 类对 a 进行完全相同的操作。我如何实现这一点并且不重复来自 A 的相同代码?如果我在 B 类中省略 foo(),它会起作用吗?或者当我在 foo() 中调用 super.foo() 时发生了什么;
回答by Jeremy
Since ClassY extends ClassX, then you can remove private ClassY b
from class B. Then you can just set your instance of ClassX to the a
instance variable. This allows foo()
to be inherited in class B, but still use the same logic and instance variable.
由于 ClassY 扩展了 ClassX,那么您可以private ClassY b
从 B 类中删除。然后您可以将 ClassX 的a
实例设置为实例变量。这允许foo()
在类 B 中继承,但仍使用相同的逻辑和实例变量。
public class A {
protected ClassX a
public void foo() {
// operations on a;
}
}
public class B extends A {
// do something to set an instance of ClassY to a; for example...
public void setClassY(ClassY b){
this.a = b;
}
}
回答by redcurry
Don't define the foo() method in B if you want the same operation as that in A. If you want a different operation as A, override the foo() method in B. If you want to extend the foo() method in B so that it first does the operation in A and then in B, then call super.foo() at the top of the method; if you want the operation in A to come after the one in B, then call super.foo() at the end of the method foo().
如果你想要和A一样的操作,就不要在B中定义foo()方法。如果你想要和A不同的操作,覆盖B中的foo()方法。如果你想扩展foo()方法在 B 中,它首先在 A 中执行操作,然后在 B 中执行操作,然后在方法顶部调用 super.foo();如果您希望 A 中的操作在 B 中的操作之后进行,则在方法 foo() 的末尾调用 super.foo()。
回答by nicholas.hauschild
It sounds like ClassX
and ClassY
would have a common interface (if they have the same methods you want to call on earch, at least). Have you considered making foo()
take in an object of the type of the common interface?
这听起来像ClassX
并且ClassY
会有一个通用的接口(如果它们至少有你想要调用的相同方法)。您是否考虑foo()
过将公共接口类型的对象作为对象?
public class A {
private ClassX a;
protected void foo(ClassXAndClassYInheritMe anObject) {
operations on anObject;
}
public void foo() {
foo(a);
}
}
public class B {
private ClassY b;
@Override
public void foo() {
foo(b);
}
}
回答by Tulio F.
You can do super.foo()
inside your overrided method.
你可以super.foo()
在你的重写方法中做。