Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of using an abstract classes vs. regular class

I have decided to start doing small coding projects on my own that focus on code quality instead of code quantity and have a question about the use of abstract classes.

Now I know the differences between abstract classes and interfaces with the biggest one (I think) being that interface allow you to only define methods that need to be implemented by classes using the interface and abstract classes allowing you to define both method and members along with default method implementation if you so desire. My question is what the the main benefit of use an abstract class vs a normal class? The only real difference between the two that I can think of is that you can not create an instance of an abstract class. Are there any other differences between the two?

like image 833
ryanzec Avatar asked Jul 05 '10 22:07

ryanzec


People also ask

Why should we use abstract class instead of normal class?

The only reason for declaring a class as abstract is so that it can't be instantiated. There are situations where you will have common functionality that is shared between a number of classes, but by itself that common functionality does not represent an object or represents an incomplete object.

What are two important differences between an abstract class and an actual class?

An abstract class cannot be directly instantiated using the new keyword. A concrete class can be directly instantiated using the new keyword. An abstract class may or may not contain abstract methods. A concrete class cannot contain an abstract method.

What is the difference between an abstract class and a normal class?

Abstract classes are similar to normal classes, with the difference that they can include abstract methods, which are methods without a body. Abstract classes cannot be instantiated.


1 Answers

Strictly from a design perspective, it is best to simplify things. I believe the best way to simplify things is to use a simple analogy. Let's use an analogy of birds...

Interface: use this when you want to enforce certain functions which need to be defined. e.g. IBird has a contract for ScreamLikeABird and Fly (interface functions). But you can get more specific and have an IOstrich that has a Run contract. You may also have an IHawk that has an Attack contract...etc.

Abstract: use this when you want to enforce base functions and have base properties. e.g. Avian could be a base class for birds which may have a function called LayEgg as well as propeties called Age, Species, NumberOfChicks...etc. These things don't/shouldn't change the behavior of a bird, since all birds lay eggs...etc. But not all birds sounds the same when it scream or flies the same way (some dont even fly)....etc.... hence they should be implemented via an interface(s).

like image 81
AlvinfromDiaspar Avatar answered Sep 23 '22 20:09

AlvinfromDiaspar