java - 抽象类与抽象类Java中的【接口(interface)+继承】

标签 java inheritance interface abstract-class

在Java上下文中,一个类是否可以通过扩展另一个非抽象类并一起实现一个接口(interface)来取代扩展抽象类的需要,这两者组合起来具有抽象类的所有方法(抽象和实现) ?

最佳答案

In context of Java, could a class replace the need of extending an abstract class by extending another non-abstract class and implementing an interface together, both of which combined have all the methods(abstract and implemented), of an abstract class?

可以吗?是的

应该吗?否

抽象类可以被具体类替换,但你将改变你的系统。

请记住:抽象类不能实例化,也不应该实例化,因为它不够“具体”,对您的业务没有意义。 (如果是的话,它一开始就不应该是一个抽象类)

如果将其具体化,开发人员将面临使用(应该是)抽象类的实例的风险。

如果您按照您建议的方式更改它:

public void doSomething(MyAbstractClass instance){
  // here we know there is an implementation provided by a subclass
}

会变成

public void doSomething(MyShouldBeAbstractClass instance){
  // here they can pass instances of the base class, which might have unsupported methods
}

例如:

public String getConcreteInformation(){ 
  throw new UnsupportedOperationException("Should be called on a child class");
}

可能会导致很多讨厌的错误

关于java - 抽象类与抽象类Java中的【接口(interface)+继承】,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46037339/

相关文章:

c# - 如何实现具有公共(public)属性但私有(private)设置方法的多个接口(interface)?

java - Eclipse 不编译 java 文件(已经尝试了可能重复的答案)

java - Android 将字符串转换为日期

c# - C#中没有继承的装饰器模式。这样对吗?

c++ - 如何在编译时检测基类的模板参数(错误)?

linux - 模拟进入 Linux 接口(interface)的数据包

java - Android Palette 仅适用于某些 RecyclerView 项目

java - 将字符串封装为 byte[] 是为了节省内存吗? ( java )

c++ - 类中静态成员的构造顺序

c# - 我可以强制一个实现类返回一个它自己类型的对象吗?