Amar M
Amar M

Reputation: 31

Method overriding vs abstract method

We use abstract method to implement it in a different sub classes for different scenarios.

Like abstract class Animal will have abstract method makeNoise(). Subclass Dog and Cat will implement this abstract method to print "bark" and "meow", respectively

But I want to know that how is it different than method overriding where we can use two classes with its own method makeNoise() for itself?

In both cases we instantiate the both sub classes to perform the actual task then how it would be efficient to use abstract method.

Upvotes: 3

Views: 6207

Answers (2)

Limnic
Limnic

Reputation: 1866

Creating a common method that gets overridden in other classes defeats the purpose of abstract classes. They are designed so they CANNOT be used until a child class extends the abstract class to further complete it (Overriding).

If you don't make Animal abstract then like all other answers say, how will you fill in its purpose?

Upvotes: 0

Manjunath
Manjunath

Reputation: 1685

An abstract method is a contract which forces its immediate subclass to implement the behaviour of all abstract methods. Where as overriding is optional and is not always a necessity for the subclasses.

Efficiency of abstract method lies in the fact that they force the immediate subclass to provide implementation. Generally speaking go for abstract over overide in cases where you do not know what would be the common default implementation for all child classes.

For your example what if we donot know what is the common noise/sound that most of the animals make. We only know that all animals make noise. So better to go for abstract. If you knew the common/default noise that most of the animals make then you could provide that implementation in Animal class as non abstract and if needed its child classes can override it if they think they make a better noise :-)

Upvotes: 6

Related Questions