在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/