![](/img/trans.png)
[英]What (not) to declare when implementing an interface with an abstract class?
[英]abstract class and interface what will be change
我们有一个抽象类Parent
,以及另外两个类: class ChildOne
和Childtwo
class ChildOne
,它们都从Parent
继承。
问题:如果我们将Parent
声明为接口,那么当ChildOne
和ChildTwo
都实现此接口时,会发生什么或更改?
语法,这些类将需要implements Parent
而不是extends Parent
在Java 7或ChildOne
,接口不能包含方法实现,因此您需要在ChildOne
和ChildTwo
重写它们。 (从Java8开始,您可以在接口中编写默认方法的实现)。
由于接口不能保存属性,因此您还需要在ChildOne
和ChildTwo
复制它们。
如果将抽象类转换为接口,则需要
假设您的定义是,当您说拒绝“如果我们拒绝将Parent作为接口”时,更改应如下。 1.您应放弃用父类编写的功能。 2.无论您要在接口中定义任何抽象函数(替换Parent),都必须为Children编写不同的独立实现。
当将Parent
作为抽象类时, ChildOne
和ChildTwo
将继承Parent
定义的非抽象方法。 这意味着,默认情况下, ChildOne
和ChildTwo
将获得Parent
的某些功能。 当ChildOne
和ChildTwo
具有某些通用功能(可以放在Parent
时,此功能特别有用。
当将Parent
作为接口时, ChildOne
和ChildTwo
将需要实现Parent
中的所有方法。
当两者都实现此接口时,
ChildOne
和ChildTwo
会发生什么或改变
这些都不会发生-它们只能扩展一些不同的类(因为在Java中,一个类只能扩展一个类,但是可以实现许多接口)。 因此,如果可能的话,最好将Parent声明为接口而不是抽象类。
如果您在Parent中定义了某些字段,构造函数或非抽象方法,则当然不可能将Parent
从抽象类更改为接口。 请记住,接口只能容纳抽象方法声明-没有字段,方法实现或构造函数声明(除非我们谈论的是静态字段/方法,但是当我们谈论继承时,这些都不成问题)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.