PHP - 如果抽象类中的所有方法都是抽象的,那么接口和抽象类之间的区别是什么 [英] PHP - if all methods in abstract class are abstract then what is the difference between interface and abstract class

查看:157
本文介绍了PHP - 如果抽象类中的所有方法都是抽象的,那么接口和抽象类之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抽象类可能有也可能没有抽象方法,但接口只有未实现的方法。那么,如果我的抽象类将其所有方法标记为抽象,那么使用接口的区别和优势是什么?

An Abstract Class may and may not have abstract methods but an interface has unimplemented methods only. So what is the difference and advantage of using an interface if my abstract class has all of its methods marked as abstract?

推荐答案

抽象类允许部分实现(参见模板方法模式),但在这种情况下,如果所有方法都是如此是抽象的,你没有看到这种好处。你可以做的另一件事是包括字段,你不仅限于方法。

An Abstract Class allows for "partial implementation" (see the template method pattern), but in this case, if all methods are abstract, you don't see that benefit. One other thing you can do is include fields, you're not just limited to methods.

请记住,抽象方法和定义的合同之间存在概念上的区别通过界面。抽象方法必须由子类覆盖,该子类通过继承实现来完成。任何多态调用(向下转换)都需要每个类一个超类,否则会遇到钻石继承问题。这种基于继承的树结构是OO设计的典型。

Remember, there's a conceptual difference between an "abstract method" and the contract defined by an interface. An abstract method has to be overridden by a subclass which is done through inheritence implementation. Any polymorphic calls (downcasting) will require one superclass per class or it would hit the diamond inheritance problem. This kind of inheritence based tree structure is typical of OO design.

作为对比,界面提供了要履行的合同的签名。只要保留签名,就可以满足许多接口的需求,因为不存在返回类层次结构以查找其他实现的问题。接口并不真正依赖于多态来实现这一点,它基于契约。

As a contrast, an interface provides a signature of a contract to fulfil. You can fulfil many interface's needs as long as you retain the signature as there is no question of going back up the class hierarchy to find other implementations. Interfaces don't really rely on polymorphism to do this, it's based on a contract.

另外需要注意的是,你可能有受保护的抽象方法,它使得没有意义在界面中做这样的事情(实际上这样做是违法的)。

The other thing of note is you may have "protected" abstract methods, it makes no sense to do such a thing in an interface (in fact it's illegal to do so).

这篇关于PHP - 如果抽象类中的所有方法都是抽象的,那么接口和抽象类之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆