What is Abstraction in Java with Example

Abstraction in Java is another core OOPs principle that provides a powerful way to manage complexity. The process of hiding complex internal implementation details of a system from users and providing only necessary functionality is called abstraction.

In other words, abstraction is a technique in Java by which we can hide the data that is not required to a user. It hides all unwanted data so that users can work only with the required data.

Abstraction removes all non-essential things and shows only important things to users. That is, every user will get the required data and will not get confused with unnecessary data.

The main purpose of abstraction is to represent the essential features without including the background details. Let’s take some real-time examples to understand the concept of abstraction in simple words.

Real-life Examples of Abstraction in Java


1. ATM Machine:

We all use an ATM machine for cash withdrawal, money transfer, retrieve min-statement, etc. in our daily life. But we don’t know internally what things are happening inside ATM machine when you insert an ATM card for performing any kind of operation. The complex internal details are hidden from the user, and only the required functionality is provided.

Realtime example of abstraction in Java

2. Car:

A car owner knows how to drive it and how to use its components such as accelerator, brake, steering wheel, and clutch. For example, a car owner knows that the accelerator pedal is used to increase the speed of car, and pressing the brake pedal stops it.

To perform these simple actions, the driver doesn’t need to know how the accelerator or brake works internally. Only the necessary functionality is exposed, and the complex mechanism is hidden.

3. Mobile Phone (SMS Example):

When you send an SMS from your mobile, you simply type the text and press “Send” button. You don’t need to know the internal processing of how the message is transmitted across networks and delivered to the recipient. The complexity is hidden.

4. Bank System:

A bank clerk can see the customer details like name, account number, and balance amount in the account. But he cannot access the sensitive information, such as staff salaries, bank profits/losses, loan details, etc.

Such data are hidden (abstracted) from him. However, when the bank manager requires knowing this data, it will be provided to the manager. Thus, there are lots of such important things in your real life that show abstraction.

In Java OOPs:

Abstraction works in the same way. You only need to call the specific classes or methods to implement specific program logic, but you don’t know how these classes or methods function internally. For example,

  • Java provides many built-in classes like ArrayList, HashMap, etc. You use their methods (add(), remove(), get(), etc.) without knowing the internal implementation.

This concept is known as abstraction in Java.

How Can We Achieve Abstraction in Java?


In Java, there are two ways to achieve or implement abstraction:

  1. Abstract class (0 to 100%)
  2. Interface (100%)

Key Point:

Java allows you to design applications with multiple levels of abstraction by combining abstract classes and interfaces, depending on project requirements. Abstract class and interface are the most common ways to achieve abstraction in Java. Let’s understand each way and learn how to implement it in Java program.

Abstract Class in Java


An abstract class in Java is a class, which is declared with an abstract keyword. It is just like a normal class but has two key differences.

  • We cannot create an object of an abstract class. Only objects of its non-abstract (or concrete) sub-classes can be created.
  • An abstract class can have zero or more abstract methods. These methods are declared but not implemented in the abstract class and must be implemented by its subclasses.
  • It can also have concrete methods with implementation. This means abstraction using an abstract class can range from 0% (no abstract methods at all) to 100% (all methods abstract).
  • A normal (concrete) class cannot have abstract methods.
  • Classloader class is a good real example of an abstract class that does not have any abstract methods.

The purpose of abstract class is to make programming more flexible by providing scopes to write abstract method in subclasses of the abstract class.

Key Points about Abstract Class

1. Abstract is a non-access modifier in Java.

  • It is applicable for classes, interfaces, methods, and inner classes.
  • It represents an incomplete class whose implementation depends on its subclasses.
  • Therefore, creating a subclass is compulsory to provide full implementation.

2. A non-abstract class is sometimes called a concrete class, as it has complete implementation.

3. The concept of abstract is not applicable to variables. You cannot declare a variable as abstract.

When to Use Abstract Class in Java?


You should use an abstract class in Java when:

  • You need to share the same method to all non-abstract subclasses with their own specific implementations. For example, you can declare an abstract method in the abstract class and allow all subclasses to implement it in their own way.
  • Moreover, you want to share common fields (data members) and concrete methods of abstract class among multiple subclasses. This avoids code duplication since the shared members are inherited by all subclasses.

Thus, an abstract class makes the program more flexible, reusable, and easier to understand by combining shared logic (common members) with customizable behavior (abstract methods).

Abstract Method in Java


A method that is declared with abstract modifier in an abstract class and has no implementation (means no body) is called abstract method in Java. It does not contain any body.

  • Abstract method has simply a signature declaration followed by a semicolon.
  • Since the abstract method does not contain any body. Therefore, it is also known as incomplete method in Java.
  • The actual implementation of the abstract method must be provided by the subclass that extends the abstract class.

Syntax

An abstract method has the following general form as given below:

abstract returntype methodName(arguments); // No body

Example:

abstract void msg(); // No body.

Key Points:

  • A concrete method is a method which has always a body (i.e. implementation). It is also called a complete method in Java.

When to Use Abstract Method in Java?


You should use an abstract method in Java in the following scenarios:

  • When the same method has to perform different tasks in different classes, depending on the object calling it.
  • When you want to force subclasses to provide their own implementation of a method.

Use of Abstract Class and Abstract Method in Java

When we write anything in a class, it is applicable to all its objects. If a method is defined in a class, it is available to all objects of a class. For example, suppose a class MyTest that contains a method calculate() that calculates addition of a given two numbers.

If you create three objects to this class, all three objects will get a copy of this method and from any object, we can call this method. Here, the requirement of all objects is the same, i.e. to calculate addition of two numbers.

Now, our requirement is changed. We want the first object calculates addition, the second object calculates subtraction, and the third object calculates multiplication. Since calculate() method has to perform three different tasks depending on the object. In such a case, how will write calculate() method in MyTest?

If we declare three methods like add(), sub(), and multiply() in MyTest, all three methods will be available for all three objects which are not advisable.

To solve this problem, we will use an abstract class and abstract method. We will declare calculate() method as abstract, it will not have any body within it.

Now, we will derive three subclasses like Addition, Subtraction, and Multiplication from class MyTest where in each subclass, we will provide a method body for calculate() method so that it can calculate different operations such as add, subtract, and multiply.

In this way, we will implement the same abstract method in three subclasses as per the requirement of objects and can perform different tasks. We can also create objects of subclasses, and respective method can be called using these objects. The hierarchy is shown in the below figure:

When to use Abstract class in Java

Example:

Let’s take an example program where abstract class MyTest has one abstract method which will be various implementations in subclasses.

package com.abstraction; 
// Abstract class
public abstract class MyTest 
{ 
   abstract void calculate(int a, int b); // No body. 
} 
// Subclass: Addition
public class Addition extends MyTest 
{ 
   void calculate(int a, int b)
   { 
      int x = a + b; 
      System.out.println(“Sum: ” +x); 
   } 
} 
// Subclass 2: Subtraction
public class Subtraction extends MyTest 
{ 
   void calculate(int a, int b)
   { 
      int y = a - b; 
      System.out.println(“Subtract: ” +y); 
   } 
} 
// Subclass 3: Multiplication
public class Multiplication extends MyTest 
{ 
   void calculate(int a, int b)
   { 
      int z = a * b; 
      System.out.println(“Multiply: ” +z); 
   } 
} 
// Main class
public class MyClass { 
public static void main(String[] args) 
{ 
 // Creating objects of classes. 
    Addition a = new Addition(); 
    Subtraction s = new Subtraction(); 
    Multiplication m = new Multiplication(); 
    
 // Calling methods by passing arguments.
    a.calculate(20, 30); 
    s.calculate(10, 5); 
    m.calculate(10, 20); 
 } 
}
Output: 
       Sum: 50 
       Subtract: 5 
       Multiply: 200

As you can observe in the above example, the requirement of every object has been fulfilled. Thus, this example perfectly shows how abstract classes and abstract methods help in achieving flexibility, reusability, and multiple implementations of the same method. I hope that you will have understood the applications of abstract class and abstract method in Java.

Features of Abstract Class in Java


There are following key features of abstract class in Java that you should keep in mind. They are:

  1. Abstract class is not a pure abstraction in Java because it can contain both abstract methods and concrete methods.
  2. In Java, object creation is not possible for an abstract class because it is a partially implemented class, not fully implemented class.
  3. An abstract class can be abstract even with no abstract method. For example, ClassLoader is abstract but does not have abstract methods.
  4. An abstract class may contain:
    • Only abstract methods
    • Only concrete methods
    • Or a combination of both
  5. Abstract class allows to define private, final, static and concrete methods. Everything is possible to define in an abstract class as per application requirements.
  6. An abstract class can have constructors, and they are called when its subclass is instantiated.
  7. It does not support multiple inheritance in Java but allows in interfaces.
  8. An abstract class can implement one or more interfaces in Java.

Rules of Abstract Class in Java


There are the following rules to define an abstract class in Java. They are:

  1. Class must be declared with abstract keyword to make an abstract class.
  2. You cannot instantiate an abstract class, but you can create objects of its subclasses provided they must implement abstract methods.
  3. If a class contains at least one abstract method, the class itself must be declared as abstract.
  4. To use methods declared in an abstract class, it must be extended by a concrete (non-abstract) class, and that class must implement (override) all abstract methods.
  5. If a new abstract method is added in the abstract class, all non-abstract subclasses which extend that abstract class, must implement the newly added abstract method. If it does not implement all the abstract methods, the class must be declared as abstract.
  6. If a new instance method is added in the abstract class, all non-abstract subclass which extends that abstract class, is not necessary to implement newly added instance method.
  7. Inside the abstract class, you can create any number of constructors. If you do not create a constructor, the compiler will create a default constructor.

Rules of Abstract Method in Java


The rules of abstract method to define in an abstract class are:

  1. Abstract method can only be declared inside an abstract class.
  2. A non-abstract class cannot have an abstract method, whether it is inherited or declared in the program.
  3. An abstract method must not provide a method body/implementation in the abstract class for which it is defined.
  4. When overriding an abstract method in a subclass, the method name and signature must match exactly with the one in the abstract class.
  5. The visibility (access modifier) of the method in the subclass cannot be reduced while overriding abstract method. For example, if the abstract method is declared protected, the subclass cannot override it as private.
  6. Abstract method cannot be static or final.
    • Static methods belong to the class, not an instance, so they cannot be overridden.
    • Final methods cannot be overridden, which contradicts the purpose of an abstract method.
  7. An abstract method cannot be private because it must be implemented in the subclass. If you declare it private, you cannot implement it from outside the class.

Examples of Abstract Class in Java


Let’s take some example programs based on these rules to understand the abstract class and abstract method concepts more clearly.

Example 1:

package com.abstraction; 
public abstract class AbsClass 
{ 
  // No abstract method here. 
} 
// Creating a subclass that inherits Abstract class. 
public class Subclass extends AbsClass { 
  public static void main(String[] args) 
  { 
    AbsClass c = new AbsClass(); // Compile-time error. 
  } 
}
Output: 
        Unresolved compilation problem: Cannot instantiate the type AbsClass

In this example, we have tried to create an object of abstract class, but the compiler show a compile-time error.

Example 2:

Let’s take an example program where an abstract class Hello contains both abstract method and instance method. The abstract method “msg2” will be implemented in Test class that extends a class Hello.

package com.abstraction; 
public abstract class Hello 
{ 
// Declaration of instance method. 
   public void msg1() 
   { 
      System.out.println("msg1-Hello"); 
   } 
   abstract public void msg2(); // abstract method.
} 
public class Test extends Hello 
{ 
// Overriding abstract method. 
   public void msg2() 
   { 
      System.out.println("msg2-Test"); 
   } 
public static void main(String[] args)
{ 
 // Creating object of subclass Test. 
    Test obj = new Test(); 
    obj.msg1(); 
    obj.msg2(); 
  } 
}
Output: 
       msg1-Hello 
       msg2-Test

In this example program, we have not implemented instance method msg1() in subclass, but abstract method msg2() has been implemented (overridden) in the subclass.

Example 3:

Let us consider an example program where an abstract class can have a data member, constructor, abstract, final, static, and instance method (non-abstract method).

package com.abstraction; 
public abstract class AbstractClass 
{ 
  int x = 10; // Data member. 
  AbstractClass()
  { 
     System.out.println("AbstractClass constructor"); 
  } 
  final void m1()
  { 
     System.out.println("Final method"); 
  } 
  void m2()
  { 
     System.out.println("Instance method"); 
  } 
  static void m3()
  { 
     System.out.println("Static method"); 
  } 
  abstract void msg(); // abstract method declaration.
} 
public class AbsTest extends AbstractClass 
{ 
   AbsTest()
   { 
      System.out.println("AbsTest class constructor"); 
   } 

// Implementation of abstract method in the subclass.
   void msg()
   { 
      System.out.println("Hello Java"); 
   } 
public static void main(String[] args) 
{ 
    AbsTest t = new AbsTest(); 
    t.msg(); 
    t.m1(); 
    t.m2(); 
    m3(); 
    System.out.println("x = " +t.x); 
  } 
}
Output: 
       AbstractClass constructor 
       AbsTest class constructor 
       Hello Java 
       Final method 
       Instance method 
       Static method 
       x = 10

In this example program, after object creation, the constructor of non-abstract subclass will be called immediately. In the first line of constructor, internally super will call the constructor of an abstract class. The control of execution will be immediately transferred to the constructor of abstract class.

Therefore, the first output is “AbstractClass constructor”. After executing abstract class constructor, control of execution again comes back to execute subclass constructor. The second output is “AbsTest class constructor”.

Why Does an Abstract Class Have a Constructor in Java?


Although we cannot create an object of an abstract class directly, an abstract class can still have a constructor. The reason is:

  • We cannot create an object of abstract class, but we can create an object of subclass of abstract class.
  • When we create an object of subclass of an abstract class, it calls the subclass constructor.
  • This subclass constructor has super in the first line that calls constructor of an abstract class.
  • If the superclass is an abstract class, its constructor is executed before the subclass constructor.

If the abstract class doesn’t have a constructor, a class that extends that abstract class will not get compiled.

Example 4:

Here, we will create an abstract class Employee that contains instance variables, constructor, and concrete method. A subclass Engineer extends abstract class Employee.

package com.abstraction; 
public abstract class Employee 
{ 
   private String name; 
   private int id; 
 
   public Employee(String name, int id)
   { 
     this.name = name; 
     this.id = id; 
   } 
// Declaration of concrete method. 
   void m1()
   { 
      System.out.println("Name: " +name); 
      System.out.println("Id: " +id); 
   } 
} 
public class Engineer extends Employee 
{ 
   public Engineer(String name, int id)
   { 
      super(name, id); // This statement is used to call super class constructor. 
   } 
public static void main(String[] args)
{ 
// Creating an object of the subclass of abstract class. 
   Engineer e = new Engineer("Deep", 10202); 
   e.m1(); 
 } 
}
Output: 
       Name: Deep 
       Id: 10202

When we have created an object of subclass, it immediately calls Engineer class constructor. In the first line of constructor, (super(name, id)) calls the Employee constructor. Thus, the superclass constructor is executing when creating an object of subclass. This initializes the name and id variables defined in the abstract class.

Now suppose if an abstract class does not allow to define constructor, in such a case, is it possible to initialize the value of non-static variables in abstract class?

Answer is no because, without object creation of abstract class, we cannot initialize non-static variables. Therefore,  an abstract class allows constructors to initialize variables.

Example 5:

Let us take an example in which an abstract class reference refers to the subclass objects. Abstract class reference can be used to call methods of the subclass.

package Abstarctclass; 
public abstract class Identity 
{ 
  abstract void getName(String name); 
  abstract void getGender(String gender); 
  abstract void getCity(String city); 
} 
public class Person extends Identity 
{ 
  void getName(String name) 
  { 
     System.out.println("Name : " +name); 
  } 
  void getGender(String gender) 
  { 
     System.out.println("Gender : " +gender); 
  } 
  void getCity(String city)
  { 
     System.out.println("City: " +city); 
  } 

// Newly added method in subclass. 
   void getCountry(String country)
   { 
      System.out.println("Country: " +country); 
   } 
 } 
public class Mainclass { 
public static void main(String[] args) 
{ 
 // Declaring abstract class reference equal to subclass object. 
    Identity i = new Person(); 
     i.getName("DEEPAK"); 
     i.getGender("MALE"); 
     i.getCity("DHANBAD"); 

 // This statement will generate a compile-time error because 
 // we cannot access newly added method in subclass using superclass reference. 
 // i.getCountry("INDIA"); 
 } 
}
Output: 
       Name: DEEPAK 
       Gender: MALE 
       City: DHANBAD

In the preceding example, we created abstract class reference that refers to its subclass object. Using superclass reference, we are accessing all methods of subclass in the main() method, except newly added method in the subclass. But if it is possible to access all the members of subclasses by creating objects of subclass, why should we need to create reference to superclass.

Why Should We Create Reference to Superclass (Abstract Class Reference)?


We create a superclass (abstract class) reference to access subclass objects because:

  • A superclass reference can hold the object of any of its subclasses. This allows polymorphism where the same reference can point to different subclass objects at runtime.
  • The superclass reference can only access the methods and variables declared in the superclass. Even though the object belongs to the subclass, the reference restricts access only to the features defined in the superclass.
  • If a subclass defines an additional method that is not declared in the superclass, the superclass reference cannot call it.

Advantage of Abstract Class in Java


The main advantages of using abstract class in Java application are as follows:

  • Abstract class makes programming better and more flexible by giving the scope of implementing abstract methods.
  • Programmers can implement an abstract method to perform different tasks depending on the need.
  • We can easily manage code.

Conclusion

In this tutorial, you have learned that abstraction in Java is a fundamental principle of the object-oriented programming system. It simplifies complex systems by hiding unnecessary details from users. Abstraction is achieved using abstract classes and interfaces. It makes the code more reusable.

By hiding implementation details from users, abstraction prevents unauthorized access and modification of data, thereby enhancing security. Hope that you have understood the how to implement abstraction in Java and practiced all example programs.