Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit from a class or an abstract class

Tags:

If you have several classes where you want them to inherit from a base class for common functionality, should you implement the base class using a class or an abstract class?

like image 460
Joan Venge Avatar asked Mar 02 '09 19:03

Joan Venge


People also ask

Can you inherit a class from an abstract class?

An abstract class cannot be inherited by structures. It can contain constructors or destructors. It can implement functions with non-Abstract methods. It cannot support multiple inheritances.

Which class should a class inherit from abstract?

If the Child class is unable to provide implementation to all abstract methods of the Parent class then we should declare that Child class as abstract so that the next level Child class should provide implementation to the remaining abstract method.

Is abstract class the same as inheritance?

The main difference between abstraction and inheritance is that abstraction allows hiding the internal details and displaying only the functionality to the users, while inheritance allows using properties and methods of an already existing class.

Can you inherit from an abstract class and an interface?

An abstract class defines the identity of a class. An interface can inherit multiple interfaces but cannot inherit a class. An abstract class can inherit a class and multiple interfaces.


2 Answers

That depends, if you never want to be able to instantiate the base class then make it abstract. Otherwise leave it as a normal class.

like image 148
Hawk Kroeger Avatar answered Nov 09 '22 23:11

Hawk Kroeger


If the base class ought not to be instantiated then make it an abstract class - if the base class needs to be instantiated then don't make it abstract.

In this example it makes sense to make the base class abstract as the base class does not have any concrete meaning:

abstract class WritingImplement {     public abstract void Write(); }  class Pencil : WritingImplement {     public override void Write() { } } 

However in this next example you can see how the base class does have concrete meaning:

class Dog {     public virtual void Bark() { } }  class GoldenRetriever : Dog {     public override void Bark() { } } 

It is all pretty subjective really - you ought to be able to make a pretty good judgment call based on the needs of your particular domain.

like image 45
Andrew Hare Avatar answered Nov 09 '22 23:11

Andrew Hare