这里是一个父类
public class Parent {
public void f() {
}
}
这是一个简单的界面。
public interface If {
public void f();
}
这是一个子类
public class Child extends Parent implements If{}
我的问题是:
虽然声称要实现接口If
的是Child
,但是接口方法是在Parent
中实现的。为什么允许这样做?
Do nothing and let Parent
's method directly implement the interface method.
Override Parent
's method even though you're not going to do anything differently, e.g.:
@Override
public void f() {
super.f();
}
...which really doesn't accomplish anything unless you have code you want to run prior to or after calling Parent
's f
.
Override f
and implement it yourself, ignoring Parent
's version. But that only makes sense if Parent
's f
does something completely different from the interface method's f
— in which case, you shouldn't be subclassing Parent
in the first place, because if you reimplement f
in terms of the interface's behavior, your f
won't satisfy the Parent#f
contract anymore (in terms of its behavior) and you'll break the "is a" rule for subclassing.
所以说,如果这一切是自然而然发生的,那么选项1就非常合理。但你可能不会有意地设置它。
Parent
的实现并从中删除了方法f
(或者更改了其签名等),那么Child
就不再有效了。 - Sva.MuChild
已经与Parent
紧密绑定,这是子类化的本质。Parent
的更改可能会影响Child
的方式有很多。 - T.J. CrowderChild
对接口作出承诺,而不是Parent
,因此更合理的做法是直接在Child
中实现接口方法,因为没有任何事情会强制Parent
去"保持它"。 - Sva.MuChild
对于 Parent
也有一个“是一个”的承诺。我已经在答案中添加了相关内容。我不认为这种情况曾经在我的 Java 编程中出现过,思考各种选项还是很有趣的。 - T.J. Crowder这是完全合法的,因为当您实现该方法时,它适用于两者。
从类的角度和接口的角度来看,单个实现将同时满足两个目的,没有任何歧义。
除非与它们存在关系,否则无法限制类或接口具有相同的方法签名,但在这种情况下不会有问题。
f
的方法。 - SomeJavaGuyParent
没有实现 任何 接口。 - Sva.Mu