Abstraction in Java – Explore Abstraction vs Encapsulation in Java

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Before we dive into the topic Abstraction in Java, yes you have guessed it right, we will understand a real-life example of abstraction. It needs the utmost dedication to understand this concept.

Let us say you are driving your favorite car. Be it a Prius, a Lamborghini, or a BMW. You are cruising across the city and you feel good. But let us zoom inside and take a look at the functioning of your brain which is basically the computer of your body.What do we see? It knows the functions accelerate(), brake(), steer() and so on.. Whenever you need to break your brain executes the function brake() which makes you push the brake pedal with your foot. But, here is the catch.

Do you know the inner workings of the brake mechanism of your car? Do you know how the brake pads decrease the velocity of the car? How does the brake fluid go from the pedal to the brake mechanisms on each wheel of your car? No right? Unless you are a car fanatic. This is abstraction. This hiding of details that are not necessary for the user is abstraction. In java, abstraction plays a huge role in designing applications. We will see all of that in this article!

Abstraction in Java

Abstraction in Java

In Java, abstraction is the process of identifying only the relevant details and ignoring the non-essential details. You can achieve abstraction by using interfaces and abstract classes. We will be learning about them in this article!

Abstraction, simply put, is the careful presentation of details which are significant. Programmers implement abstraction which helps them in writing efficient code.

Types of Abstraction in Java

Types of Abstraction in Java

There are two kinds of abstraction in java. They are as follows:

a. Data Abstraction in Java

This is the process of creating complex datatypes and revealing only the useful parts of the data type for programmers to use. This improves the implementation over time. For example, standard templates such as Linked Lists and Array Lists or HashMaps in Java reduce the complexity and allow the programmer to directly use the data structure instead of redefining them.

b. Control Abstraction in Java

In large scale software development, there is frequent reuse of code throughout the project. If all the people implement the same functionality, they should only have to write the particular function once and then execute it whenever needed. This process of creating a unit definition of a piece of work and reusing it whenever necessary is control abstraction. An example would be functions in Java.

Structured programming implements control abstraction in Java.

Abstract Classes and Abstract Methods in Java

Before we understand what abstract classes are, let us learn what abstract methods are. Abstract methods are methods that lack a concrete definition. This means you just have to declare the function prototype and not write anything in between the curly braces. If a class contains one or more methods that are abstract in nature, i.e, lacking definition, then the class is an abstract class.

How to Declare abstract classes and abstract methods:

a. You always have to declare an abstract class with an abstract keyword.

b. Note that you do not need to have all the methods in the abstract class as abstract. You can also have concrete methods inside an abstract class.

c. Once you declare the abstract methods you have to redefine these methods in the subclass. This goes on to say that method overriding is compulsory if you inherit an abstract class.

d. However, you can ignore the definition if the class you are inheriting and the child class are abstract classes. This means you do not have to override the methods in the parent class if your current class is also abstract like the parent class.

e. Another important point to note is that the class has to be abstract if any one of its methods is abstract.

f. An abstract class cannot have instances of itself. In layman’s terms, you cannot have an object of a class that is abstract.

Syntax:

The basic syntax of declaring an abstract class is

abstract class <class-name>
{
//class definition
}
and that of an abstract method is

abstract <return-type><method-name>(<parameters>);

Let us take a look at an example to better understand this concept.

Java program to illustrate the use of abstract classes in Java:

package com.dataflair.abstraction;
abstract class Area {
  abstract void area();
}
class Square extends Area {
  void area() {
    System.out.println("The area of a square is (side)^2");
  }
}
class Rectangle extends Area {
  void area() {
    System.out.println("Area of a rectangle is (length*breadth)");
  }
}
class Circle extends Area {
  void area() {
    System.out.println("The area of a circle is PI*radius*radius");
  }

}
public class AbstractClass {
  public static void main(String[] args) {
    Rectangle r = new Rectangle();
    r.area();
    Circle c = new Circle();
    c.area();
    Square s = new Square();
    s.area();
  }
}

Output:

Area of a rectangle is (length*breadth)
The area of a circle is PI*radius*radius
The area of a square is (side)^2

Notice how the same abstract method area() has different implementations throughout the classes. You can also have different constructors for different classes.

Need for Abstract Classes in Java

At first glance, you may think that this whole idea of having abstract classes is redundant because we cannot instantiate an abstract class. But upon careful inspection, you will start to notice that abstract classes are built for dynamic software. Software goes through updates all the time. You add functionalities, remove bugs. Abstraction is a very important design principle that allows us to design flexible software.

To add or design a new feature, you simply have to mention the new method in your abstract class and override it with necessary details. This allows you to leverage Polymorphism and inheritance for supporting future changes.

Interfaces in Java

Interfaces are similar to abstract classes, they have method prototypes but they do not have method definitions. You can define an interface as the blueprint of a class.

If a class implements an interface, it needs to override each and every method of the interface unless the class itself is an abstract class. Let us take a look at the basic syntax of an interface

Syntax of Java Interface

interface <interface-name>
{
//constant fields;
//abstract method 1;
//abstract method 2;
…
}

When we implement this interface we call it by using the implements keyword. Now you might be thinking as to why introduce interfaces when we already have abstract classes. Right?

Difference between Java Interface and Abstract Class

  • Abstract classes can have non-final variables while interfaces can have public, static, and final variables only.
  • You have to use interfaces and abstract classes based upon your requirements.
  • Interfaces are useful to achieve total abstraction or implement multiple inheritance in Java.
  • You can achieve loose coupling by implementing interfaces. Loose coupling means the independence of two separate events. If two events are independent of each other, they are loosely coupled. For example, When you change your clothes you do not need to change your entire body. That is loose coupling.
  • You can have multiple interface implementations in your class.
  • Also, a single interface can extend more than one interface.

New features of Interfaces in Java

If you are using Java version 8 or newer, you can add default implementations to your interfaces.

For example, Suppose you need to have a new method in an interface. Now the old class definitions will throw errors because they need to implement all the methods in the interface. The default implementation saves us from this trouble and allows us to dynamically change the number of methods in the interface.

You can also have static methods inside an interface which you can call without an object, However, these methods are non-inheritable. If you are using java 9 or newer, you can have static, private, and private static methods inside your interface.

Program to illustrate the usage of interfaces in Java:

package com.dataflair.abstraction;
interface in {
  void run();
  static void statmethod() //static method
  {
    System.out.println("This is a static method");

  }
default void sleep() //default method
  {
    System.out.println("Both humans and dogs love to sleep");
  }
}
class Dog implements in {
  public void run() {
    System.out.println("A dog runs with the help of four legs");
  }

}
class Human implements in {
  public void run() {
    System.out.println("A human runs with the help of two legs");
  }
}
class Interface {
  public static void main(String[] args) {
    Dog d = new Dog();
    d.run();
    Human h = new Human();
    h.run(); in .statmethod();
    h.sleep();

  }
}

Output:

A dog runs with the help of four legs
A human runs with the help of two legs
This is a static method
Both humans and dogs love to sleep

Program to illustrate the use of inheritance of abstract methods in Java:

package com.dataflair.abstraction;
interface inface {
  void func1();
  void func2();

}

abstract class Class1 implements inface {
  public void func2() {
    System.out.println("I am the second function!");
  }
  //This class does not override all functions hence this is also abstract
}

class Class2 extends Class1 {
  public void func1() {
    System.out.println("I am the first function!");
  }

}

class Abstraction {
  public static void main(String args[]) {
    Class2 obj = new Class2();
    obj.func1();
    obj.func2();
  }
}

Output:

I am the first function!
I am the second function!

Advantages of Abstraction in Java

a. You can group several related sibling classes and methods inside a class.
b. The design and implementation gets benefitted as it reduces the complexity of the codebase.
c. Abstraction reduces code duplication.
d. The security of the application improves because only the necessary details are visible to the user.

Java Encapsulation vs Abstraction

AbstractionEncapsulation
This implementation solves the issues at the design level. This implementation solves the issues at the implementation level.
Abstraction essentially means the hiding of unnecessary information and revealing information which is essential. Encapsulation means the bundling up of data and the code into a single unit. 
Abstraction lets the programmer focus on the result of an operation regardless of how the operation gets executed. Encapsulation hides the internal details of the execution of a program for security reasons. 
We use interfaces and abstract classes to implement abstraction. We use access modifiers such as public, private, and protected to implement encapsulation. 

Applying Abstraction to a Graphical User Interface (GUI)

Let’s consider a real-world example of how abstraction can be applied in Java GUI development. Imagine you’re building a program with a button that displays a message box when clicked. Here’s how abstraction can benefit you:

1. Abstract Button Class: Create an abstract class Button with an abstract method onClick(). This method defines the functionality that happens when the button is clicked, but doesn’t specify the implementation details.

2. Concrete Button Subclass: Create a concrete subclass MessageBoxButton that extends the Button and overrides the onClick() method. In this method, you can implement the logic to display the message box.

3. Using the Button: In your main program, you can create an instance of MessageBoxButton and add it to your GUI. When the button is clicked, the overridden onClick() method in MessageBoxButton will be called, displaying the message box.

Points to Remember

There are certain points to remember while implementing abstraction in our programs.

a. Abstract classes cannot have objects.
b. If there is a single abstract method in a class, then the class must be an abstract class.
c. An abstract class may have concrete methods.
d. Abstract classes support non-final variables.
e. When you inherit an abstract class into a child class, you must override all the methods in the abstract class or make the child class abstract.

Summary

This was all about abstraction in Java. We learned about implementing abstract classes, methods. We also learned about interfaces and how they can help programmers achieve total abstraction in their programs.

Your opinion matters
Please write your valuable feedback about DataFlair on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

1 Response

  1. Ravi says:

    This was the best ever explanation with perfect examples I have ever seen for most of the java topics.

Leave a Reply

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