为什么实现接口的抽象类可能会错过接口方法之一的声明/实现? [英] Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

查看:177
本文介绍了为什么实现接口的抽象类可能会错过接口方法之一的声明/实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您使用抽象类来实现接口时,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.

按照示例代码,尝试创建<$ c的子类$ c> AbstractThing 没有实现 m2 方法,看看编译器给你带来了什么错误。它会强制你实现这个方法。

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.

这篇关于为什么实现接口的抽象类可能会错过接口方法之一的声明/实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆