DEV Community

Kanishka Shrivastava
Kanishka Shrivastava

Posted on

#java #oop #abstraction #programming

Java Concepts I’m Mastering – Part 7: Abstraction in Java (Abstract Class vs Interface)

Continuing my journey of mastering Java fundamentals.

Today’s focus: Abstraction — hiding implementation details and showing only essential behavior.

Abstraction helps us focus on what an object does, not how it does it.

-> Abstract Class

An abstract class:

Can have abstract methods (without body)

Can have normal methods (with body)

Cannot be instantiated

abstract class Vehicle {
    abstract void start();

    void fuelType() {
        System.out.println("Petrol or Diesel");
    }
}

class Car extends Vehicle {
    void start() {
        System.out.println("Car starts with key");
    }
}
Enter fullscreen mode Exit fullscreen mode

Used when classes share common behavior.

-> Interface

An interface:

Contains method declarations (by default public & abstract)

Supports multiple inheritance

Defines a contract

interface Payment {
    void pay();
}

class UPI implements Payment {
    public void pay() {
        System.out.println("Payment via UPI");
    }
}

Enter fullscreen mode Exit fullscreen mode

Used when you want unrelated classes to follow the same contract.

Key Differences
Abstract Class Interface
Can have constructors Cannot have constructors
Can have instance variables Only constants
Supports single inheritance Supports multiple inheritance
Used for shared base behavior Used for defining contracts

What I Learned

Use abstract class when classes are closely related.

Use interface when defining capability/behavior.

Abstraction makes systems scalable and loosely coupled.

This concept is heavily used in frameworks and real-world applications.

Next in the series: Encapsulation & Data Hiding in Java

Top comments (0)