抽象类的目的是什么? [英] What is the purpose of abstract classes?

查看:47
本文介绍了抽象类的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 PHP 中学习 OOP,但我对接口和抽象类有些困惑.它们都没有实现,只有定义,并且应该通过它们的子类来实现.抽象类的哪一部分清楚地将它们与接口区分开来?此外,由于它们明显的相似性,我应该基于什么原因决定使用一种而不是另一种?

I am trying to learn OOP in PHP, and I have some confusion about interfaces and abstract classes. They both contain no implementations, only definitions, and should be implemented through their sub-classes. What part of abstract classes clearly distinguishes them from interfaces? Also, due to their apparent similarities, based on what reasons should I decide to use one over the other?

推荐答案

可以创建包含具体成员(例如方法或属性)的抽象类.您仍然无法直接实例化抽象类,但任何实例化的子类都可以从抽象类中定义的已实现成员中受益.

It is possible to create abstract classes that contain concrete members, such as methods or properties. You still can't instantiate the abstract class directly, but any instantiated sub-classes can benefit from implemented members defined in the abstract class.

相比之下,接口从不包含任何实现逻辑.由每个实现类来提供接口中定义的所有成员的实现.

An interface, by comparison, never contains any implementation logic. It is down to each implementing class to provide the implementation of all members defined in the interface.

就我如何看待差异而言,抽象是那种类型的类的子类.例如Dog 是一种Animal.我将界面视为一种does-a 关系.例如ICanDisplayImages 告诉我实现类可以显示图像,但没有告诉我该类实际代表什么.

In terms of how I view the differences, a sub-class of an abstract is-a class of that type. e.g. Dog is an Animal. I see an interface as a does-a relationship. e.g. ICanDisplayImages tells me that the implementing class can display images, but tells me nothing about what the class actually represents.

这篇关于抽象类的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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