Abstraction Tutorial With Example In JAVA

In Java, Abstraction is one of the major building block. It is a process of hiding internal working and showing only necessary details. In simple form abstraction means:

  • Show Functionality
  • Hide Complexity

Important Note: Interface is used to achieve 100% Abstraction in JAVA. Here we only discuss Abstraction in full details but we recommend you to learn Abstraction and Interface topic simultaneously as both topics are similar with little bit difference.


Explanation Of Abstraction:

The best explanation of Abstraction is using the common example of sending SMS. When a user send SMS, he simply enter the address, type message in the text box and send it. He doesn’t know what is happening behind the scene when this message is getting send to the other user. So here implementation details has been hided from the user and only functionality is presented to user. This is achieved in JAVA either through Abstraction or Interface.


Key Learning Points On Abstraction:

Before we share syntax you first need to understand abstract class, abstract methods and why/how to extend Abstract class:

What Is Abstract Class:

An abstract class is declared with abstract keyword which may contain methods without body, with body or mixture of both. If a class have at least one method without body then it has to be declared abstract.

Important Note: Method without body means method without any functionality or implementation.

In the below example you can see one method calling is without body. So here class has to be declared abstract because it has one method without body.

abstract class Mobile{
abstract void calling();
abstract void messaging()
{
System.out.println("Messaging");
}
}

What Is Abstract Method:

The methods without body or methods with only signatures are called abstract methods. The abstract method doesn’t have any implementation details. It is declared using abstract keyword before method name. For example, calling method is an abstract method.

abstract void calling();

Syntax: of Abstract Method

abstract void method_name();

Important Note: In order to use abstract method we first need to override that method in subclass (i.e. child class).

Why And How To Extend Abstract Class:

As now you already know Abstract class may contains abstract method without any implementation and thus we cannot instantiate abstract class. In case we try instantiating it, the object might be useless because methods inside abstract class may not have any implementation at all. So to avoid this situation, JAVA doesn’t allow us to instantiate abstract class.

We first need to extend abstract class where we will do the implementation of those abstract method and then we instantiate this new class.

So let’s see how to extend Abstract class:

Step 1: First we define abstract class with abstract method:

abstract class Mobile{
abstract calling(); //Method without body
}

Step 2: Now we extends abstract class and implement abstract methods:

class Samsung extends Mobile{
void calling();
{
System.out.println("Start Calling");
}
}

Pro Note: An example of abstract class is AbstractMap which is part of collection framework include TreeMap, HashMap and ConcurrentHashMap and share many methods like isEmpty(), put() , get(), containValue() , containKey() etc that AbstractMap defines.


Syntax Of Abstraction:

The syntax of abstraction start with abstract keyword before class name. It then contains mixture of abstract and non-abstract methods.

abstract class <ClassName>{
//Mixture of abstract methods(Without body/implementation) and non-abstract methods(with body/implementation)
//If it contains atleast one abstract method then a class has to be declared abstract
}

Examples Of Abstraction:

Example 1: Lets now understand abstraction concept using real life examples of different sounds created by animals. For example Cat does Meow and Lion Does Roar. We will display different sounds using Abstraction in JAVA.

Step 1: First create a new project in Eclipse and create a abstract class Sound. Below is the code of Sound.java

abstract class Sound {
    
//Non-abstract method i.e. method with implementation
    public void soundmessage(){
        System.out.print("Animal Sound");
    }
    
//Abstract method i.e. without body/implementation
    abstract void sound();

}

Step 2: Now create another class name Cat which extends Sound class. Here we will implement abstract sound() method for Cat. Below is the code of Cat.java

class Cat extends Sound{

void sound(){
	soundmessage();
	System.out.println(" of Cat: Meow");
}

}

Step 3: In the same way we are creating another Lion class which extends Sound class. Here also we will implement the sound() method but for Lion. Below is the code of Lion.java:

class Lion extends Sound {
	
	void sound(){
		soundmessage();
		System.out.println(" of Lion: Roar");
	}

}

Step 4: Now create AnimalSound main class. Here first we will create object of Cat & Lion class and then we will call sound() method on these objects. Below is the code of AnimalSound.java

public class AnimalSound {

	public static void main(String[] args) {
		
		Cat cat = new Cat();
		cat.sound();
		
		Lion lion = new Lion();
		lion.sound();
	}

}

Output:

Now run the program and you will see sounds of Cat and Lion printed.

Animal Sound of Cat: Meow
Animal Sound of Lion: Roar

Conclusion: So you can see how useful is Abstraction. We just define mixture of abstract and non-abstract methods in Abstract class and then implement abstract method in child class (i.e. sub class) according to requirement. In the end same method gives different result depending on Objects of which sub-class. Remember we can’t instantiate Abstract class as discussed earlier.

Example 2: In second Abstraction example we simply display a text “AbhiAndroid” by using an abstract method of an abstract Base class. In this, Child class extends the Base class and override the display method and then prints the text as shown in below example.

Here in this example we have provided lots of explanation in the code itself as comments.

Below is the code of Base.java

abstract class Base //abstract class
{
abstract void display(); //abstract method
}

Below is the code of Child.java and also main function of class

class Child extends Base  //child class which extends the property of  base class
{
void   display() // override method of  base class
 {
   System.out.println("AbhiAndroid");  //prints the text “AbhiAndroid” as an output
}
public static void main(String args[]) //main function of class
{
  Child c=new Child(); //create an object of child class
  c.display(); //call the display method of child class with the help of  object
}
}

OUTPUT:

AbhiAndroid

Conclusion: In the above example, Base is abstract class that contain abstract method display(). Its implementation is provided by the Child class.


Importance Of Abstraction

Below is the some major important points of abstraction in java.

  • Abstraction helps to reduce the complexity and also improves the maintainability of the system.
  • Abstraction gives more power to the object oriented programming languages when used with the concepts like encapsulation and polymorphism.
  • Abstraction is used to provide solution to real world problem.

Difference Between Abstract Class And Interface:

Abstract class is quite similar to interface like both contain abstract method and also we can’t initiate both of them. But below are the some key differences between  both the topics:

Abstract class:

  1. Abstract class can extend only one class at a time.
  2. Abstract class can have both abstract (method without implementation) and concrete methods (method with implementation).
  3. In abstract class ‘abstract’ keyword is used to declare a method as abstract.
  4. Abstract class can have protected, public and public abstract methods.
  5. Abstract class can have static, final or static final variables with any access specifier.

Interface:

  1. Interface can extend any number of interfaces at a time.
  2. Interface can only have abstract methods, they cannot have concrete methods.
  3. In interfaces, “abstract” keyword is optional to declare a method as an abstract because all the methods are abstract by default.
  4. Interfaces can have only public abstract methods i.e by default.
  5. Interfaces can have only static final variable i.e by default.

Ask Your Question Or Leave A Reply

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