且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中的接口和抽象类混淆与示例

更新时间:2023-12-03 22:44:46

记住使用抽象类或接口时的基本概念。

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.