简体   繁体   English

使用抽象类和接口

[英]Using abstract classes and Interfaces

If I have three classes 如果我有三堂课

class A

class B extends A

class C extends A

Would using abstract classes or interfaces give me any type of errors or affect the way I implement the program? 使用抽象类或接口会给我带来任何类型的错误还是会影响我实现程序的方式?

Unless you need to share implementation, favor interfaces. 除非需要共享实现,否则请选择接口。

If you need to share implementation, think carefully if an abstract class is the right way to accomplish this. 如果需要共享实现,请仔细考虑抽象类是否是实现此目的的正确方法。

Inheritance is a powerful tool, but can easily create an unmaintainable mess (I have been guilty here). 继承是一个功能强大的工具,但可以轻松创建一个无法维护的混乱(我在这里一直感到内)。

But to answer your question - no, there is nothing inherent in this setup that would cause an "error". 但是要回答您的问题-不,此设置没有内在因素,不会引起“错误”。

You should generally prefer interfaces whenever you can. 通常,您应该尽可能地选择接口。 Java's lack of multiple inheritance quickly becomes a limiting factor if you use classes for that. 如果您使用类,则Java缺少多重继承很快就会成为限制因素。

Yes. 是。 Abstract classes trade a shorter way of reusing implementation for the flexibility to provide multiple interfaces to the same object. 抽象类以一种更短的方法来重用实现,以灵活地为同一对象提供多个接口。

Unless you're playing code-golf, choosing the flexibility of interfaces is usually the better option. 除非您正在玩代码高尔夫,否则通常选择接口的灵活性是更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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