Abstraction in Java with realtime Example

Abstraction is also one of the fundamental principal of object-oriented programming languages and a key element of good software design. Many times beginners find it difficult to understand this, so we will see this concept with some real world examples to make it easy to understand.

What is Abstraction in Java

Abstraction is a process of hiding the internal details or implementations from the user and showing only relevant or abstract(brief or short) information to user. Abstractions says that, show only those information to user which is essential or useful for them and hide all other information which is not essential for them.

More programmatically, abstraction in java is the process of hiding implementation details of object's feature and showing only the essential information of feature to the user. Abstraction lets you focus more on what an object does rather than how it does.

Real time example of abstraction

To take a real time example, when we login to any social networking site like Facebook, Twitter, Linkedin etc, we enter our user id and password and then we get logged in. Here we don't know how they are processing the data or what logic or algorithm they are using for login. Those informations are abstracted/hidden from us, since those are not essential for us. This is basically what abstraction is.

Another real world example of abstraction could be your TV remote. The remote has different functions like on/off, change channel, increase/decrease volume etc. You use these functionalities just pressing the button. The internal mechanism of these functionalities are abstracted from you as those are not essential for you to know.

In fact every object that you see around yourself has some degree of abstraction in one way or other, be it your Mobile, Laptop, AC, Fan, Car or whatever. The internal working of these objects are hidden from us.

How to achieve abstraction in Java

In java generally we use interfaces and abstract classes to achieve abstraction. An interface or abstract class is something that is not concrete, something which is abstract/incomplete because these types contains abstract methods whose functionality or the internal mechanism is not defined by the interfaces/abstract classes itself, rather it is defined/implemented by other classes. For example if I declare an interface like below :

 interface Shape {
    public void draw();
    public double getArea();
 }   

When you look the above interface, you don't know the functionality or implementation detail of it's abstract methods, you only know the name of method(feature), the functionality will be given by some other class. This is what the abstraction is, wherein you only know the features.

Now before we start to understand abstraction with program, let's see a brief detail about abstract method and abstract classes. We will see the complete details about both topic in later tutorial. If you want to know about interfaces, refer interface in java tutorial.

Abstract Method
A method without a body is known as an abstract method. Abstract methods do not have an implementation, they only have method signature. These methods are declared in an abstract class or interface. The following code declares an abstract method draw.

 public abstract void draw(); 

Inside the interfaces we don't need to apply the abstract keyword with method declaration as it is internally applied by interfaces but in case of abstract classes, we need to apply abstract keyword explicitly with abstract methods.

Abstract Class
An abstract class is a class which is declared using abstract keyword. Abstract classes are very similar as normal classes except that they can have abstract methods as well along with concrete methods. We can not create the object of abstract classes. Following code defines an abstract class MyAbstractClass.

 abstract class MyAbstractClass {
    // Class body
 }   

An abstract class may contain one or more abstract methods while an interface contains only(Before Java 8) abstract methods. Interfaces allows you to achieve complete abstraction while abstract classes can be used to achieve partial as well as complete abstraction. Abstract classes are generally used for partial abstraction.

Java Program of abstraction using Interface

The classes in below program implements the Shape interface that we discussed above.

 class Circle implements Shape {
    private double radius;
     
    public Circle(double r) { 
       this.radius = r; 
    } 
    public void draw() { 
       System.out.println("Drawing Circle"); 
    } 
    public double getArea() { 
       return Math.PI*radius*radius; 
    } 
 }
 
 class Rectangle implements Shape {
    private double length;
    private double width;
     
    public Rectangle(double length, double width) { 
       this.length = length; 
       this.width = width; 
    } 
    public void draw() { 
       System.out.println("Drawing Rectangle"); 
    } 
    public double getArea() { 
       return length*width; 
    } 
 }

Similar to Circle and Rectangle there can be other shape type as well that can implement Shape interface. Now in order to access the features(getArea, draw) of a shape, all you need to know is the implementing class, you don't need to know how they have implemented the features, that can be hidden from you, this is what abstraction is. The class given below accesses these features.

 public class AbstractionTest { 
     public static void main (String args[]) {
         // Shape object referring to circle.
         Shape circle = new Circle(10);
         circle.draw(); 
         System.out.println("Area of given circle = "+circle.getArea());
         // Shape object referring to rectangle.
         Shape rect = new Rectangle(10,10);
         rect.draw(); 
         System.out.println("Area of given rectangle = "+rect.getArea());
     }
 }

Output:

Drawing Circle
Area of given circle = 314.1592653589793
Drawing Rectangle
Area of given rectangle = 100.0

In order to run above program successfully, ensure that you have declared all the classes and interfaces given above inside same directory.

Java Program of abstraction using abstract class

The program below contains an abstract class TwoDShape which contains one abstract and one concrete method.

 abstract class TwoDShape {
    private double length;
    private double width;
    
    public TwoDShape(double length, double width) {
       this.length = length; 
       this.width = width;    
     }
    // Declaring abstract method
    public abstract void draw();
    // Defining concrete method
    public double getArea() { 
      return length*width; 
    } 
 }
 
 public class Rectangle extends TwoDShape { 
    public Rectangle(double length, double width) {
       super(length,width);    
     }
    public void draw() { 
       System.out.println("Drawing Rectangle"); 
     }     
    public static void main (String args[]) {
       // TwoDShape object referring to rectangle.
       TwoDShape rect = new Rectangle(10,10);
       rect.draw(); 
       System.out.println("Area of given rectangle = "+rect.getArea());
    }
 }

Output:

Drawing Rectangle
Area of given rectangle = 100.0

Here the abstract class TwoDShape gives the definition of getArea method while hides the implementation of draw method. The implementation of draw method is given by the implementing class which is Rectangle class. So for us the TwoDShape class is an example of partial abstraction.

Example of Abstraction in Java language

In Java we can take Map interface as an example. The Map interface has declared many abstract methods like get, put, remove, size etc. The classes like HashMap, TreeMap, Hashtable etc implements this Map interface and provides the functionality of these methods. We use these implemented classes and it's implemented methods in our programs without knowing how they have been implemented, as that is not essential for us. So for us the Map interface is an abstraction.

In fact everything in our program has some abstraction behind it. For example the very common line System.out.println() that we use for printing the value on console has some abstraction. We just know that it prints the value on console but how it does we don't know, that is hidden from us since that is not essential for us.

Advantage of abstraction in Java

Some of advantages of using abstraction are :

  • It reduces the complexity of viewing the things as it shows only essential information.
  • It helps to decouple the behavior(method) and it's implementation in a software/application.
  • It allows the flexibility to modify/change implementation logic if needed, as long as the outcome of behavior is not affected by the modification.
  • It helps to increase security of an application or program as only important details are provided to the user.
  • It also helps to avoid code duplication and increases reusability.

Should I really focus more to know the abstraction in detail ?

If you are a designer/architect who designs the solution or application, then it's definitely helpful for you to have good understanding about abstraction feature, otherwise having a basic idea about it is enough.

That's all about abstraction in java. Both abstract classes and interfaces are used to achieve abstraction and both have their own importance while designing a Java application, but developers generally prefer to use interfaces over abstract classes for abstraction.