Write a post
Published Apr 14, 2017Last updated Apr 21, 2017

Java 101: Why do we need to define abstract methods in a class, when in future we will very well need to override it?

Java 101: Why do we need to define abstract methods in a class, when in future we will very well need to override it?

I read this question in Quora and was thinking that this is a very relevant question. Only that, we never think of it, when we are learning about abstract classes. We sort of accept that declaring abstract classes is a norm. Introspecting further I found a few reasons, which I enumerated in my answer. Here it goes:

Why do we need to define abstract methods in a class, when in future we will very well need to override it?

So that the class can defer the behavior of the method to the specific implementations. If we take the most used and cliched example of class Shape, the method area() does not know what to return. The area of a Shape is determined by the kind of Shape it is - a Square or a Circle. Hence, Square and Circle classes have to add the implementation of the method area.

Now what if there is no abstract method area in Shape and just in Square and Circle classes? Let's say, next day, you add another subclass Pentagon and forget to add the method area(). Yet, every Shape must have an area. How do you ensure that happens through code? By declaring the abstract method area() in Shape. This will guarantee that Pentagon class​ will not build until area is overridden.

Photo credit: Google

Discover and read more posts from Rashmi
get started
Enjoy this post?

Leave a like and comment for Rashmi

1