Abstraction in Java – Learn with its Types and Real-life Examples

The extent to which a module hides its internal data and other implementation details from the other modules is the most important factor that distinguishes a well-designed Object-Oriented module from other modules.

A well-designed module hides all of its implementation details and cleanly separates its interface from its implementation. These modules then communicate with each other only through the interfaces. This concept is supported with the help of Abstraction in Java.

The meaning of the word “Abstraction”, in general words, is the process of working with ideas rather than their implementation.

For example, consider the example of an email, the user does not know about the complex details such as what happens just after sending an email, which protocol is used by the server to send the message.

Therefore, we just need to mention the address of the receiver, type the content and click the send button.

This is basically called Abstraction in which the complex details are being hidden from the users.

Similarly, in Object-oriented programming, abstraction is a process of providing functionality to the users by hiding its implementation details from them. In other words, the user will have just the knowledge of what an entity is doing instead of its internal working.

Java Abstraction Advantages

Today, we will discuss the very important concept of Object-Oriented Programming, which is Abstraction.

Abstraction in Java

An Abstraction is a process of exposing all the necessary details and hiding the rest. In Java, Data Abstraction is defined as the process of reducing the object to its essence so that only the necessary characteristics are exposed to the users.

Abstraction defines an object in terms of its properties (attributes), behavior (methods), and interfaces (means of communicating with other objects).

Real-life Example for Java Abstraction

If we want to process something from the real world, we have to extract the essential characteristics of that object. Consider the example, shown in the figure below.

Java Abstraction Example

Here, you can see that an Owner is interested in details like Car description, service history, etc; Garage Personnel are interested in details like License, work description, bill, owner, etc; and Registration Office interested in details like vehicle identification number, current owner, license plate, etc.

It means each application identifies the details that are important to it.

Abstraction can be seen as the technique of filtering out the unnecessary details of an object so that there remain only the useful characteristics that define it. Abstraction focuses on the perceived behavior of the entity. It provides an external view of the entity.

How to Achieve Abstraction in Java?

In Java, we can achieve Data Abstraction using Abstract classes and interfaces.
Interfaces allow 100% abstraction (complete abstraction). Interfaces allow you to abstract the implementation completely.

Abstract classes allow 0 to 100% abstraction (partial to complete abstraction) because abstract classes can contain concrete methods that have the implementation which results in a partial abstraction.

Abstract Classes in Java

  • An Abstract class is a class whose objects can’t be created. An Abstract class is created through the use of the abstract keyword. It is used to represent a concept.
  • An abstract class can have abstract methods (methods without body) as well as non-abstract methods or concrete methods (methods with the body). A non-abstract class cannot have abstract methods.
  • The class has to be declared as abstract if it contains at least one abstract method.
  • An abstract class does not allow you to create objects of its type. In this case, we can only use the objects of its subclass.
  • Using an abstract class, we can achieve 0 to 100% abstraction.
  • There is always a default constructor in an abstract class, it can also have a parameterized constructor.
  • The abstract class can also contain final and static methods.

Get to know more about Classes in Java in detail with Techvidvan.

Syntax of declaring an abstract class:

To declare an abstract class we use the keyword abstract. The syntax is given below:

abstract class ClassName
{
//class body
}

Note: We can not instantiate abstract classes i.e., we can not create objects or instances from the abstract classes.

Abstract Methods in Java

  • Abstract methods are methods with no implementation and without a method body. They do not contain any method statement.
  • An abstract method is declared with an abstract keyword.
  • The declaration of an abstract method must end with a semicolon ;
  • The child classes which inherit the abstract class must provide the implementation of these inherited abstract methods.

For a better understanding, take a deep insight into the concept of Java Methods.

Syntax of declaring abstract methods:

access-specifier abstract return-type method-name();

Example of Abstract class and Abstract methods

package com.techvidvan.abstraction;
//parent class
abstract class BaseClass
{
  //abstract method
  abstract public void show1();

  //concrete method
  public void show2()
  {
    System.out.println("Concrete method of parent class");
  }
}
//child class
class ChildClass extends BaseClass
{
  // Must Override this method while extending the Parent class
  public void show1()
  {
    System.out.println("Overriding the abstract method of the parent class");
  }

  //Overriding concrete method is not compulsory
  public voidshow2()
  {
    System.out.println("Overriding concrete method of the parent class");
  }
}
public class AbstractionDemo
{
  public static void main(String[] args)
  {
    /* we can't create object of the parent class hence we are creating object of the child class */
    ChildClass obj = new ChildClass();
  obj.show1();
  obj.show 2();
  }
}

Output:

Overriding abstract method of the parent class
Overriding concrete method of the parent class

Why do we need Abstract Classes in Java?

If we can’t create an object from abstract classes and neither can’t use them, then what is the need for abstract classes?

To answer this question, let’s take a situation where we want to create a class that just declares the general form or structure or guidelines of a particular idea, without giving a complete implementation of every method.

And, we want that this generalized form or structure of the class can be used by all of its child classes, and the child classes will impose these guidelines by fulfilling all the implementation details according to the need.

There is no need for implementing the method in the parent class thus, we can declare these methods as abstract in the parent class. That is, we will not provide any method body or implementation of these abstract methods.

Making these methods as abstract will enforce all the derived classes to implement these abstract methods otherwise, there will be a compilation error in your code.

Code to understand the concept of Abstraction in Java:

package com.techvidvan.abstraction;
abstract class GeometricShapes
{
  String nameOfShape;
  //abstract methods
  abstract double calculateArea();
  public abstract String toString();
  //constructor
  public GeometricShapes(String nameOfShape)
  {
    System.out.println("Inside the Constructor of GeometricShapes class ");
    this.nameOfShape = nameOfShape;
  }
  //non-abstract method
  public String getNameOfShape()
  {
    return nameOfShape;
  }
}
class Circle extends GeometricShapes
{
  double radius;
  public Circle(String nameOfShape,double radius)
  {
    super(nameOfShape);
    System.out.println("Inside the Constructor of Circle class ");
    this.radius = radius;
  }
  //implementing the methods
  @Override
  double calculateArea()
  {
    return Math.PI * Math.pow(radius, 2);
  }
  @Override
  public String toString()
  {
    return "Name of the shape is " + super.nameOfShape +
        " and its area is: " + calculateArea();
  }
}
class Square extends GeometricShapes
{
  double length;
  public Square(String nameOfShape,double length)
  {
    //calling Shape constructor
    super(nameOfShape);
    System.out.println("Inside the Constructor of Square class ");
    this.length = length;
  }
  //implementing the methods
  @Override
  double calculateArea()
  {
    return length * length;
  }
  @Override
  public String toString()
  {
    return "Name of the Shape is " + super.nameOfShape +
        " and its area is: " + calculateArea();
  }
}
public class AbstractionDemo
{
  public static void main(String[] args)
  {
    GeometricShapes shapeObject1 = new Circle("Circle", 6.5);
    System.out.println(shapeObject1.toString());

    GeometricShapes shapeObject2 = new Square("Rectangle",8);
    System.out.println(shapeObject2.toString());
  }
}

Output:

Inside the Constructor of GeometricShapes class
Inside the Constructor of Circle class
Name of the shape is Circle and its area is: 132.73228961416876
Inside the Constructor of GeometricShapes class
Inside the Constructor of Square class
Name of the Shape is Rectangle and its area is: 64.0

Why can’t we create an object of an Abstract Class?

You might be wondering why can’t we instantiate an abstract class or create an object from it? Suppose, if Java allows you to create an object of the abstract class and use this object.

Now, if someone calls the abstract method through the object of the abstract class then what would happen? There would not be any actual implementation of the called method.

Also, an abstract class is like a guideline or a template that has to be extended by its child classes for the implementation.

Code to illustrate that object creation of an abstract class is invalid:

As discussed above, we cannot instantiate an abstract class. This program throws a compilation error.

package com.techvidvan.abstraction;
//Parent class
abstract class ParentClass
{
  //Abstract method
  abstract public void showDetails();
}
//Child class
class ChildClass extends ParentClass
{
  public void showDetails()
  {
    System.out.print("Overriding Abstract method of the parent class ");
  }
}
public class AbstractionDemo
{
  public static void main(String args[])
  {
    //error: You can't create object of an abstract class
    ParentClass obj = new ParentClass();
    obj.showDetails();
  }
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Cannot instantiate the type ParentClass

Types of Abstraction in Java

Abstraction can be of two types:

1. Data abstraction

Data abstraction is the most common type of abstraction in which we create complex data types such as HashMap or HashSet, and hide its implementation details from the users and display only the meaningful operations to interact with the data type.

The benefit of this approach solves the performance issues and improves the implementation over time. Any changes which occur while improving the performance, do not reflect on the code present on the client-side.

2. Control abstraction

Control abstraction is the process of determining all such statements which are similar and repeat over many times and expose them as a single unit of work. We normally use this type of abstraction is when we want to create a function to perform any given task.

Advantages of Abstraction in Java

  • It reduces the complexity of viewing things.
  • Increases software reuse and avoids code duplication: Loosely-coupled classes often prove useful in other contexts.
  • It helps to increase the security and confidentiality of an application as only necessary details are exposed to the user.
  • Eases the burden of maintenance – Classes can be understood more quickly and debugged with little fear of harming other modules.

Data Encapsulation vs Data Abstraction in Java

  • Encapsulation is one step beyond abstraction.
  • Data Encapsulation is hiding data or information while Abstraction is hiding the implementation details.
  • Encapsulation binds the data members and methods together while data abstraction deals with showing the external details of an entity to the user and hiding the details of its implementation.
  • Abstraction provides access to a specific part of data while encapsulation hides the data.

Things to Remember

  • In Java, you can not create an object from the abstract class using the new operator. If you try to instantiate an abstract class, it will give a compilation error.
  • An abstract class can have a constructor.
  • It can contain both abstract as well as concrete methods. An abstract method just has the declaration but not any method body.
  • In Java, only classes or methods can be declared as abstract, we can not declare a variable as abstract.
  • We use the keyword abstract to declare both class and method as abstract.
  • If we declare any method as abstract, the class automatically needs to become an abstract class.

Summary

Through Data Abstraction we can reduce a real-world entity into its essential defining features and show only what is necessary to the users. The concept of data abstraction is totally based on abstract classes in Java.

Here we come to the end of our Java article. Now let’s look at what all we have learned. In this article, we have discussed the importance of Abstraction in Java with real-life examples.

We also covered the detailed description of abstract classes and abstract methods in Java with their syntax and examples. Now, you might have understood the importance of Abstraction in OOPs and also how to implement it in your codes.

Thank you for reading our article. Do share this Java article on Social Media.

Happy Learning 🙂