Abstract Class & Abstract Methods in Java

Abstract Class –

A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body). It needs to be extended and its method implemented. It cannot be instantiated.

Abstract Methods –

A method that is declared as abstract and does not have implementation is known as abstract method.

Understanding the real use of Abstract Class & Abstract Methods –

abstract class in java example1

In this example, we have a Shape super class which is inherited by 3 sub classes – Rectangle, Triangle and Circle. The task here is to have 1 Area() method in the parent/super class and is inherited by all 3 child/sub classes. However, every child class has its own definition to calculate area as the area formula for each shape is different. Also, since our parent class shape is not known, we cannot have a valid method definition in the parent class. So this is where we can use Abstract class concept and make the Area() method in the parent class as abstract. Once we inherit from the Shape class, the subclasses can have their respective implementations done according to their needs.

Important Points about Abstract Classes & Abstract Methods in Java –

1. In Java, an instance of an abstract class cannot be created, we can have references of abstract class type though.

Derived fun() called

2. An abstract class can contain constructors in Java. And a constructor of abstract class is called when an instance of a inherited class is created. For example – 

Base Constructor Called
Derived Constructor Called

3. In Java, we can have an abstract class without any abstract method. This allows us to create classes that cannot be instantiated, but can only be inherited.

Base fun() called

4. Abstract classes can also have final methods (methods that cannot be overridden). For example, the following program compiles and runs fine.

Derived fun() called

Some More important rules to be followed –

  • If there is any abstract method in a class, that class must be abstract.
  • If you are extending any abstract class that have abstract method, you must either provide the implementation of the method or make this class abstract.


Leave a Reply

Your email address will not be published. Required fields are marked *