简体   繁体   中英

Abstract class with only abstract methods

Given an abstract class with only abstract methods, what would be the differences between this and an interface?

The only difference I can see would be related to the ability to use multiple inheritance with the interfaces.

Are there other important differences in this situation which would dictate whether to do this or use an interface instead?

将非公共方法声明为抽象的能力......将抽象类设置为从其他父项派生的能力,以及通过它向父子提供父方法的能力......确定你的Ctor将获得什么的能力以及通过该力量派生类来“知道”某些数据

  1. Abstract classes are meant to be inherited from, and when one class inherits from another it means that there is a strong relationship between the 2 classes. For instance, if we have an abstract base class called "Canine", any deriving class should be an animal that belongs to the Canine family (like a Dog or a Wolf). The reason we use the word "should" is because it is up to the Java developer to ensure that relationship is maintained.

With an interface on the other hand, the relationship between the interface itself and the class implementing the interface is not necessarily strong. For example, if we have a class called "House", that class could also implement an interface called "AirConditioning". Having air conditioning not really an essential part of a House (although some may argue that point), and the relationship is not as strong as, say, the relationship between a “TownHouse” class and the "House" class or the relationship between an “Apartment” class that derives from a “House” class.

Because a TownHouse is a type of House, that relationship is very strong, and would be more appropriately defined through inheritance instead of interfaces.

So, we can summarize this first point by saying that an abstract class would be more appropriate when there is a strong relationship between the abstract class and the classes that will derive from it. Again, this is because an abstract class is very closely linked to inheritance, which implies a strong relationship. But, with interfaces there need not be a strong relationship between the interface and the classes that implement the interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM