Categories: OOPS

What is abstraction in Java and how to achieve it?

Index

What is Abstraction in Java?

Ways of Achieving Abstraction in Java.

Abstract Class in Java

Syntax

abstract class ClassName {

    // Regular (concrete) method
    returnType anotherMethod() {
        // Method body
    }
}

// Subclass that extends the abstract class
class SubClassName extends ClassName {

    // Must provide implementation for all abstract methods
    @Override
    returnType methodName() {
        // Method body
    }
}

Key points to remember

class ClassName extends SuperClassName implements InterfaceName {
    // class body (fields, constructors, methods, etc.)
}

Understanding Abstract Class with the help of a code

// Abstract class
abstract class Animal {

    // Abstract method (no body)
    abstract void makeSound();

    // Concrete method
    void sleep() {
        System.out.println("Zzz");
    }
}

// Subclass
class Dog extends Animal {

    // Implementation of abstract method
    @Override
    void makeSound() {
        System.out.println("Woof");
    }
}

// Main class
class Main {
    public static void main(String[] args) {
      // Animal a = new Animal() ❌ This will not work,
      
        Dog dog = new Dog(); // ✅ This will work
        
        dog.makeSound(); // Outputs "Woof"
        dog.sleep();     // Outputs "Zzz"
    }
}

Output

Abstract Class

abstract class Animal {

    // Abstract method (no body)
    abstract void makeSound();

    // Concrete method
    void sleep() {
        System.out.println("Zzz");
    }
}

Subclass

class Dog extends Animal {

    // Implementation of abstract method
    @Override
    void makeSound() {
        System.out.println("Woof");
    }
}

Main Method

class Main {
    public static void main(String[] args) {
      // Animal a = new Animal() ❌ This will not work,
      
        Dog dog = new Dog(); // ✅ This will work
        
        dog.makeSound(); // Outputs "Woof"
        dog.sleep();     // Outputs "Zzz"
    }
}

An Alternative Approach

 Dog a = new Dog();
Animal a = new Dog();
public class Test {
  public static void main(String[] args) {
    Animal a = new Dog();
    a.sleep();
    a.makeSound();
  }
}
abstract class Animal {
    // Abstract method (no body)
    abstract void makeSound();

    // Regular method
    void sleep() {
        System.out.println("Sleeping...");
    }
}

// Subclass (must override abstract method)
class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark!");
    }
}

Output

Abstract Method

Syntax

abstract class ClassName {
    abstract returnType methodName(parameters);
}

Difference between Abstract Method and Concrete Method

Difference between Abstract and Concrete Methods

Interface

public interface Animal {

    void makeSound(); // abstract method

    void sleep(); // abstract method

}

Important Points about Interface

interface A {   }  ===  abstract interface A {   }
interface A { 
      // int id;  // Compilation error
      int id = 20;
   }
interface A {
    int calculateArea();
}

interface B {
    int calculateArea();
}

class MyClass implements A, B {

    @Override
    public int calculateArea() {
        // Defining once is enough since both interfaces have the same method signature
        int length = 5;
        int breadth = 4;
        return length * breadth;
    }

    public static void main(String[] args) {
        MyClass obj = new MyClass();
        System.out.println("Area: " + obj.calculateArea());
    }
}
interface A { 
     int calulateArea();
   }

 interface B { 
     void calulateArea();
   }     

 class MyClass implements A, B {
    // Not possible to define calculateArea() for both interfaces   
 }
interface MyInterface { 
     void print();
   }    

 class MyClass implements MyInterface {
    public void print() {
        System.out.println("Inside print method");
     }

    public void message() {
        System.out.println("Inside message method");
     }

    public static void main(String args []) {
      MyInterface obj = new MyClass(); // Assigning MyClass object into MyInterface type
      // obj.message(); // Compilation error
      obj.print(); // prints "Inside print method"
    }
 }

This behavior is intentional and is a fundamental concept of polymorphism and abstraction in object-oriented programming. By assigning an object to an interface type, we can effectively treat the object as an instance of the interface, which can only access the members (methods and properties) defined in the interface contract.

interface X {
    int id = 10;
}

interface Y {
    int id = 20;
}

class MyClass implements X, Y {
    public static void main(String[] args) {
        // System.out.println(id); // ❌ Compilation error: ambiguous reference
        System.out.println(X.id); // ✅ Access X.id — prints 10
        System.out.println(Y.id); // ✅ Access Y.id — prints 20
    }
}
interface A {
    int id = 35; // public static final by default

    void test(); // abstract method
}

class MyClass implements A {

    public void test() {
        id = 30; // ❌ Compilation error: cannot assign a value to final variable 'id'
    }
}
class MyClass implements A {
    int id = 35; // now it's a regular instance variable

    public void test() {
        id = 30; // ✅ OK now
    }
}

Understanding Interface with the help of code

interface Vehicle {

    // Constants
    double MAX_SPEED = 200.0; // public, static, and final by default

    // Abstract methods
    void start();
    void accelerate(double speed);
    void brake();
    double getCurrentSpeed();
}

class Car implements Vehicle {

    private double currentSpeed;

    @Override
    public void start() {
        System.out.println("Car started.");
    }

    @Override
    public void accelerate(double speed) {
        currentSpeed += speed;
        System.out.println("Car accelerated to " + currentSpeed + " km/h.");
    }

    @Override
    public void brake() {
        currentSpeed = 0;
        System.out.println("Car stopped.");
    }

    @Override
    public double getCurrentSpeed() {
        return currentSpeed;
    }
}

public class Main {

    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.start();
        myCar.accelerate(50.0);
        System.out.println("Current speed: " + myCar.getCurrentSpeed() + " km/h");
        myCar.brake();
    }
}

Output

The Interface Declaration

The Implementation Part

The Main Method

Nested Interface

Syntax

interface first{  

     interface second{  

         // body

     }  

}
class abc{

    interface _interface_name{

       // body

    }

}

Difference between Abstract class and interface

Difference between Abstract class and interface

Similarity between Abstract Class and Interface

When to use Abstract Class VS When to use interface

Advantages of Abstraction in Java

Disadvantages of Abstraction in Java

Conclusion

Abstraction in Java FAQ’s

Q1. What is the difference between Encapsulation and Abstraction

Ans. Encapsulation is the practice of bundling data and methods within a single unit, like a class, and controlling their access, whereas abstraction is about hiding complex implementation details and exposing only the essential functionalities.

Q2. What is the benefit of using abstract classes?
Q3. Can we create an object of the Abstract class?

Ans. No, we cannot create an object of an abstract class directly. We can only create objects of subclasses that extend the abstract class and provide implementations for its abstract methods.

Q4. Can an abstract class have a constructor?

Ans. Yes, an abstract class can have a constructor. The constructor is called when an instance of a subclass is created. This is useful for initializing common properties that are shared among all subclasses.

Q5. Can an abstract class be final in Java?

Ans. No, an abstract class cannot be declared as final in Java because a final class cannot be subclassed, and an abstract class needs to be subclassed to provide implementations for its abstract methods.

Q6. Why use interfaces when we have abstract classes?

Ans. The reason is that abstract classes may contain non-final variables, whereas variables in the interface are final, public, and static.

Ateev Duggal

I am Ateev Duggal, a front-end web developer, and a blogger. I write blogs mainly on React JS and have an experience of over 1.5 years of freelancing. I have worked on both static and dynamic projects again using React JS like a table to show clients data which was fetched using API, a review slider, pagination component, etc, and many websites like Parent, landing pages for Ataota, and many more. Some of my blogs have been published on freecodecamp, dev.to, Medium, geeks for geeks, and many other blogging platforms and developer's communities. My Primary skills not only include React JS but HTML5, CSS3, JS, Jquery, Git, and Bootstrap also. You can visit my GitHub Profile and LinkedIn profile for more information about me or you can visit my Website at tekolio.com

Share
Published by
Ateev Duggal

Recent Posts

What is Inheritance in Java and why is it important?

Inheritance in Java is a mechanism of creating a new class or interface from an…

2 months ago

Understanding the Fundamentals of OOPS in Java

In this blog, we will not only understand the concepts of OOPS in Java in…

3 months ago

OOPS Concepts 101: What Are the Key Concepts You Need to Know?

Object-Oriented Programming System (OOPS) is a programming paradigm built around the concept of objects —…

3 months ago

How to Detect a Click Outside of a React Component using Hooks?

In this blog, we will learn How to Detect a Click Outside of a React…

2 years ago

How to Implement Infinite Scrolling in React by Making a Custom Hook

learn How to Use Hooks to Create Infinite Scrolling in React by making a custom…

2 years ago

How to build a Movie App in React using TMDB API?

React Movie App or Movie App in React is a fun project that every React…

2 years ago