Abstraction in Java

Abstraction is a methodology of hiding the implementation of internal details and showing the functionality to the users.

Example: Mobile Phone.

Abstraction In Java

A layman who is using mobile phone doesn’t know how it works internally but he can make phone calls.

Abstraction in Java is achieved using abstract classes and interfaces. Let’s see what is Abstract Class and Interface in detail.

Abstract Class:

We can easily identify whether a class is an abstract class or not. A class which contains abstract keyword in its declaration then it is an Abstract Class.

Syntax:

Points to remember:

1. Abstract classes may or may not include abstract methods
2. If a class is declared abstract then it cannot be instantiated.
3. If a class has abstract method then we have to declare the class as abstract class
4. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

Abstract Method:

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

In order to use an abstract method, you need to override that method in sub class.

Let’s see an example:

To create an abstract class, just use the abstract keyword before the class keyword, in the class declaration.

Let’s try to instantiate the AbstractSuperClass class in the following way

When you compile the above class, the output will be as follows

Output:

Now let’s Inherit the abstract class and see.

Inheriting the Abstract Class

Output:

We use abstraction when we know that our class should have some methods but we are not sure how exactly those methods should function. Assume, I am creating a class of Vehicle which should have a method called start(). There will be some other subclass of this Vehicle class such as Car, Bike and these two subclasses use start() method. But the implementation of start() method in Car is different from Bike. So in this case I don’t implement the start() method in Vehicle class and implement those in subclasses.

In the above program we have seen abstract method in the abstract class. Abstract classes doesn’t give 100% abstraction since abstract class allows concrete methods. With abstract class we can achieve partial abstraction where as we can achieve 100% abstraction with interface which we see in Interface section.

Must Read: Java Tutorial

Rajkumar SM is a founder of SoftwareTestingMaterial. He is a certified Software Test Engineer by profession and blogger & youtuber by choice. He has an extensive experience in the field of Software Testing. He writes here about Software Testing which includes both Manual and Automation Testing. He loves to be with his wife and cute little kid 'Freedom'.

Leave a Comment

Share via
Copy link
Powered by Social Snap