简体   繁体   中英

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. 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? 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. If a developer wants to create some basic Dog class for other developers or for himself to extend he declares the class as abstract. You can't instantiate the Dog class directly (nobody can), but you can extend Dog by your own class. SmartDog extends Dog etc.

All methods that are declared to be abstract by the Dog class must be implemented manually in each class that extends Dog.

For example, the abstract class Dog has an abstract method 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() .

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