Abstraction in Java – Abstract Class

May 12, 2017

Abstraction in Java:

Abstraction is a process of hiding the implementation details of the method and just show the functionality to someone which uses this method.

It can also we defined that in abstraction, we show only important things and hides other details from the user.

Abstraction lets you focus on what the object does instead of how it does.

There are two ways to achieve Abstraction:

  • Abstract Class (0 to 100% abstraction)
  • Inheritance (100% abstraction)

Abstract Class:

An abstract class is one which is declared as abstract. It may or may not have abstract methods. Now the question comes that “What is an abstract method?”

Abstract Method is one which is declared without an implementation. For example:

In the above class, we created two methods: mathsClass() and englishClass(); out of these two methods – mathsClass() is an abstract method whereas the other one is a normal method.

A class can be created without an abstract method, but an abstract method can only be created in an abstract class.

When a class extends an abstract class. It must implement all the abstract methods in the extended class.

Let us consider an example to understand abstract class in the practical world:

Let say there is a class called shape, which calculates the volume of different solid shapes – cone and cuboid (with a square base).

Volume of any solid shape = area of base * height;

Area of base for cone = PI * radius * radius;

Area of base for cuboid with square base = side * side;

Here, the implementation of calculating areas for both cone and cuboid is different. So, I will create three classes here – Shape, Cone, and Cuboid;

Shape Class will have two methods – calculateVolume() (with implementation) and calculateArea() (as an abstract method).

Cone and Cuboid classes will extend Shape class and the implementation of calculateArea() method is a must. Both will have their own way of implementation. Refer below code for better understanding.

Shape Class:

Cuboid Class:

Cone Class:

Demo Shape:

In the Demo Class, we are just calling calculateVolume() method, functionality is known to the user but the way it is implemented is hidden. This is an example of abstraction.

When to create an Abstract Class:

  • When you want to share the code between closely related classes.
  • When you expect that the class extending the abstract class have many methods and variables as common or require access modifiers other than public (say private and protected).
  • When you want to declare non-static and non-final variables.

PS: For any questions, queries or feedback. Feel free to write us at saurabh@qatechhub.com or support@qatechhub.com


About the Author


Follow Saurabh:

Leave a Comment: