What is abstraction in Java and how to achieve it?

Share your love

Index

What is Abstraction in Java?

Real World Example of Abstraction in Java

Ways of Achieving 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

Output of the Sample Java Code
Understanding Abstract Class in Java through an example

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"
    }
}
Compilation error for abstract classes

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

Output of the Sample Java Code

Abstract Method

Important points of Abstract Methods

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
    }
}
Important points of interface

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.

Share your love

3 Comments

  1. you are in reality a good webmaster The website loading velocity is amazing It sort of feels that youre doing any distinctive trick Also The contents are masterwork you have done a fantastic job in this topic

  2. Its like you read my mind You appear to know a lot about this like you wrote the book in it or something I think that you could do with some pics to drive the message home a little bit but instead of that this is fantastic blog An excellent read I will certainly be back

  3. “Mind = blown! 🌟 This is exactly the comprehensive breakdown I needed. Your expertise shines through in every paragraph. Thanks for sharing such well-researched content.”

Comments are closed.