Java Essentials: Inheritance, Interfaces, and Abstract Classes

Site Admin · 11 Sep 2026 · 8 views

Inheritance in Java

Inheritance lets one class build on another. The keyword extends creates a subclass that inherits the fields and methods of its parent. A subclass can override methods with the @Override annotation to supply its own behavior.

class Animal {
    public void speak() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("Woof");
    }
}

Java only allows a class to extend one parent, which is called single inheritance. That keeps the rules simple and predictable. To share behavior across unrelated classes, use an interface.

Interfaces Define Contracts

An interface lists the methods a class promises to implement. It describes what the class can do, not how it does it. A class implements an interface with the implements keyword and can implement several at once.

interface Drawable {
    void draw();
}

class Circle implements Drawable {
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

Any code that only cares about Drawable can accept every implementation. This is the core of programming against interfaces instead of concrete classes. Interfaces can also ship default methods, which provide a ready-made implementation that classes may override.

Abstract Classes Are Half-Finished

An abstract class sits between a concrete class and an interface. It cannot be instantiated, but it can hold fields, constructors, and fully implemented methods as well as abstract methods that subclasses must complete.

abstract class Shape {
    abstract double area();
}

class Square extends Shape {
    private double side;

    Square(double side) {
        this.side = side;
    }

    double area() {
        return side * side;
    }
}

Use an abstract class when the hierarchy is close and you want shared state. Use an interface when you want a contract that unrelated classes can honor.

Key Points

  • extends creates inheritance; @Override marks a method that replaces a parent version.
  • Java supports single inheritance for classes and multiple interfaces.
  • Interfaces define a contract, with optional default method bodies.
  • Abstract classes hold shared state and force subclasses to finish abstract methods.
Share this post:

Comments (0)

Please login or register to comment.