问题描述
我们可以扩展一个类,但是我们不能实现一个类。我们可以实现一个接口,但不能扩展接口。在什么情况下我们应该使用扩展?
extends
用于扩展基类的
class ClassX扩展ClassY {
...
}
或扩展界面:
interface InterfaceA extends InterfaceB {
...
}
请注意,界面不能实现其他接口(很可能是因为它们没有实现)。
Java不会对类与接口强加任何命名约定(与 IFoo
用于.NET世界中的接口),而是使用 extends
和 implements
表示程序员的差异:
class ClassA extends ClassB implements Interface C,InterfaceD {
...
}
您可以清楚地看到您正在基于 ClassB
中的现有实现,并且还实现两个接口的方法。
We can extend a class but we cannot implement a class. We can implement an interface, but cannot extend an interface.
In what cases should we be using extends?
extends
is used for either extending a base class:
class ClassX extends ClassY {
...
}
or extending an interface:
interface InterfaceA extends InterfaceB {
...
}
Note that interfaces cannot implement other interfaces (most likely because they have no implementation).
Java doesn't impose any naming conventions for classes vs. interfaces (in contrast to IFoo
for interfaces in the .NET world) and instead uses the difference between extends
and implements
to signify the difference to the programmer:
class ClassA extends ClassB implements InterfaceC, InterfaceD {
...
}
Here you can clearly see that you're building upon an existing implementation in ClassB
and also implement the methods from two interfaces.
这篇关于何时使用扩展和何时使用界面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!