更新时间:2023-12-03 22:53:40
记住使用抽象类或接口时的基本概念.
Remember the basic concept when using abstract classes or interfaces.
当要扩展的类与实现它的类更紧密地耦合时,即当两者都具有父子关系时,将使用抽象类.
Abstract classes are used when class to extended is more closely coupled to the class implementing it, i.e when both have a parent-child relation.
例如:
abstract class Dog {}
class Breed1 extends Dog {}
class Breed2 extends Dog {}
Breed1
和 Breed2
都是狗的类型,并且有一些与狗相同的行为.
Breed1
and Breed2
are both types of a dog and has some common behavior as a dog.
然而,当实现类具有可以从类中获取以实现的功能时使用接口.
Whereas, an interface is used when implementing class has a feature it can take from the class to implemented.
interface Animal {
void eat();
void noise();
}
class Tiger implements Animal {}
class Dog implements Animal {}
Tiger
和 Dog
是两个不同的类别,但都吃和发出声音,它们是不同的.所以他们可以使用 Animal
的食物和噪音.
Tiger
and Dog
are two different category but both eat and make noises ,which are different. So they can use eat and noise from Animal
.