What is the point of having non abstract methods in the abstract class if a new object of the abstract class can't be created?

StackOverflow https://stackoverflow.com/questions/16008762

Question

An abstract class can have both abstract and non abstract methods. What is the point of having non abstract methods in the abstract class if a new object of the abstract class can't be created?

I know you can override the non-abstract method in a child class and then use it through the object of the child class. But if you are doing that, what is the need of having the non-abstract method with an implementation in the first place?

Was it helpful?

Solution

Think more or google more.

  1. If your child classes have the common functionality then why you will override the method in every class? you can use the base class(which is abstract in this case) method.There comes the need of non-abtract(concrete as they called mostly) methods.
  2. while having abstract method there(as you know already i think), we can override according to our requirement.
  3. If you need all methods should be override in every child classes according to their requirement, then you can go for Interface.

OTHER TIPS

Simple answer: Reuse and maintainability.

Suppose there are 4 concrete classes extending your abstract class which are all going to share some behaviors.

In this case it is better to implement the method in abstract class rather than defining it separately in all your concrete classes.

Concrete subclasses can use methods in the abstract superclass. So all shared functionality between subclasses can go into the base abstract class.

Code reusage. If you don't override non-abstract methods in your inheriting class(es) you inherit them from the abstract class.

To instead have them in the subclass violates the principle of DRY (don't repeat yourself): if all the subclasses have the same function, why write it repeatedly in every class?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top