问题描述
当您使用抽象类来实现接口时,Java 中会发生一件奇怪的事情:接口的某些方法可能完全丢失(即既不存在抽象声明,也不存在实际实现),但编译器不会抱怨.
A curious thing happens in Java when you use an abstract class to implement an interface: some of the interface's methods can be completely missing (i.e. neither an abstract declaration or an actual implementation is present), but the compiler does not complain.
例如,给定接口:
public interface IAnything {
void m1();
void m2();
void m3();
}
以下抽象类在没有警告或错误的情况下被愉快地编译:
the following abstract class gets merrily compiled without a warning or an error:
public abstract class AbstractThing implements IAnything {
public void m1() {}
public void m3() {}
}
你能解释一下原因吗?
推荐答案
那是因为如果一个类是抽象的,那么根据定义,你需要创建它的子类来实例化.子类将需要(编译器)实现抽象类遗漏的任何接口方法.
That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate. The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.
按照您的示例代码,尝试在不实现 m2
方法的情况下创建 AbstractThing
的子类,然后查看编译器给您带来的错误.它会强制你实现这个方法.
Following your example code, try making a subclass of AbstractThing
without implementing the m2
method and see what errors the compiler gives you. It will force you to implement this method.
这篇关于为什么实现接口的抽象类会错过接口方法之一的声明/实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!