简体   繁体   English

继承时抽象类和非抽象类有什么区别

[英]What is the difference of abstract class and non-abstract class when inheriting

I have searched for hours of the advantages of using a abstract class over a non-abstract class in php. 我已经在php中搜索了使用抽象类优于非抽象类的优势。 I know that the abstract class can not be instantiated which is a good feature of singleton design pattern. 我知道不能实例化抽象类,这是单例设计模式的一个很好的功能。 But my point is, since they both can serve as a base class, is there any other reason to use an abstract class? 但是我的观点是,由于它们都可以充当基类,因此还有其他理由使用抽象类吗? All of the answers like this one What are the advantage if i use abstract class in php? 像这样的所有答案如果我在php中使用抽象类,什么好处? I found didn't mention this, they just answered another question, namely, what is the advantage of using a base class? 我发现没有提到这一点,他们只是回答了另一个问题,即使用基类的好处是什么? So, my question is that is there any reason to use an abstract base class other than a normal base class except for that it cannot be instantiated? 因此,我的问题是,除了不能实例化抽象类之外,是否有任何理由使用抽象基类?

An abstract class cannot be directly instantiated, but it can contain both abstract and non-abstract methods. 抽象类不能直接实例化,但可以包含抽象和非抽象方法。

If you extend an abstract class, you have to either implement all its abstract functions, or make the subclass abstract. 如果扩展抽象类,则必须实现其所有抽象功能,或者使子类抽象。

You cannot override a regular method and make it abstract, but you must (eventually) override all abstract methods and make them non-abstract. 您不能覆盖常规方法并将其抽象,但是您必须(最终)覆盖所有抽象方法并使它们抽象。

Abstract keywords are used to label classes or methods as patterns. 抽象关键字用于将类或方法标记为模式。 It's similar to interfaces but can contain variables and implementations of methods. 它类似于接口,但可以包含变量和方法的实现。

There are a lot of misunderstandings concerning abstract classes. 关于抽象类有很多误解。 Here is an example of an abstract Dog class. 这是抽象Dog类的示例。 If a developer wants to create some basic Dog class for other developers or for himself to extend he declares the class as abstract. 如果开发人员想要为其他开发人员或自己扩展创建一些基本的Dog类,则将其声明为抽象类。 You can't instantiate the Dog class directly (nobody can), but you can extend Dog by your own class. 您不能直接实例化Dog类(没有人可以实例化),但是您可以通过自己的类扩展Dog。 SmartDog extends Dog etc. SmartDog扩展了Dog等

All methods that are declared to be abstract by the Dog class must be implemented manually in each class that extends Dog. Dog类声明为抽象的所有方法必须在扩展Dog的每个类中手动实现。

For example, the abstract class Dog has an abstract method Dog::Bark() . 例如,抽象class Dog具有抽象方法Dog::Bark() But all Dogs bark differently. 但是所有的狗吠叫都不同。 So in each Dog-subclasses you must describe HOW that dog barks concretely, so you must define eg SmartDog::Bark() . 因此,在每个Dog子类中,您必须具体描述狗吠的方式,因此必须定义例如SmartDog::Bark()

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

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