Abstract Classes and Interfaces

Loading

Abstract Classes and Interfaces are two key concepts in Java that enable abstraction and define contracts for classes. They are used to achieve abstraction, one of the four pillars of Object-Oriented Programming (OOP). Below is a detailed explanation of abstract classes and interfaces, including their differences, usage, and examples.


1. Abstract Classes

An abstract class is a class that cannot be instantiated directly. It is declared using the abstract keyword and can contain both abstract methods (methods without a body) and concrete methods (methods with a body).

Key Features of Abstract Classes:

  1. Cannot Be Instantiated: You cannot create an object of an abstract class.
  2. Can Have Abstract Methods: Methods without a body, which must be implemented by subclasses.
  3. Can Have Concrete Methods: Methods with a body, which can be inherited by subclasses.
  4. Can Have Fields: Abstract classes can have instance variables.
  5. Constructors: Abstract classes can have constructors, which are called when a subclass is instantiated.

Syntax:

abstract class ClassName {
    // Fields
    data_type fieldName;

    // Abstract method (no body)
    abstract return_type methodName(parameters);

    // Concrete method (with body)
    return_type methodName(parameters) {
        // Method body
    }
}

Example:

abstract class Animal {
    String name;

    // Constructor
    Animal(String name) {
        this.name = name;
    }

    // Abstract method
    abstract void sound();

    // Concrete method
    void sleep() {
        System.out.println(name + " is sleeping.");
    }
}

class Dog extends Animal {
    Dog(String name) {
        super(name); // Call superclass constructor
    }

    // Implement abstract method
    @Override
    void sound() {
        System.out.println(name + " barks.");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog("Buddy");
        myDog.sound(); // Calls overridden method
        myDog.sleep(); // Calls inherited method
    }
}

2. Interfaces

An interface is a reference type in Java that is similar to a class but contains only abstract methods (before Java 8). From Java 8 onwards, interfaces can also have default methods and static methods with a body. Interfaces are declared using the interface keyword.

Key Features of Interfaces:

  1. Cannot Be Instantiated: You cannot create an object of an interface.
  2. Abstract Methods: All methods in an interface are abstract by default (no body).
  3. Default Methods: Methods with a body, introduced in Java 8.
  4. Static Methods: Methods with a body, introduced in Java 8.
  5. Fields: All fields in an interface are public, static, and final by default.
  6. No Constructors: Interfaces cannot have constructors.

Syntax:

interface InterfaceName {
    // Abstract method (no body)
    return_type methodName(parameters);

    // Default method (with body)
    default return_type methodName(parameters) {
        // Method body
    }

    // Static method (with body)
    static return_type methodName(parameters) {
        // Method body
    }
}

Example:

interface Animal {
    // Abstract method
    void sound();

    // Default method
    default void sleep() {
        System.out.println("This animal is sleeping.");
    }

    // Static method
    static void info() {
        System.out.println("This is an animal interface.");
    }
}

class Dog implements Animal {
    // Implement abstract method
    @Override
    public void sound() {
        System.out.println("The dog barks.");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.sound(); // Calls overridden method
        myDog.sleep(); // Calls default method
        Animal.info(); // Calls static method
    }
}

3. Differences Between Abstract Classes and Interfaces

FeatureAbstract ClassInterface
Keywordabstract classinterface
InstantiationCannot be instantiated directly.Cannot be instantiated directly.
MethodsCan have abstract and concrete methods.Can have abstract, default, and static methods.
FieldsCan have instance variables.Fields are public, static, and final by default.
ConstructorsCan have constructors.Cannot have constructors.
Multiple InheritanceA class can extend only one abstract class.A class can implement multiple interfaces.
PurposeProvide a common base class for subclasses.Define a contract for classes to follow.

4. When to Use Abstract Classes vs Interfaces

Use Abstract Classes When:

  • You want to share code among multiple related classes.
  • You need to declare non-static or non-final fields.
  • You want to provide a common base class with some default behavior.

Use Interfaces When:

  • You want to define a contract for unrelated classes to follow.
  • You need to support multiple inheritance (a class can implement multiple interfaces).
  • You want to provide default or static methods (Java 8+).

5. Example Program Combining Abstract Classes and Interfaces

// Abstract class
abstract class Vehicle {
    String type;

    Vehicle(String type) {
        this.type = type;
    }

    abstract void start();

    void stop() {
        System.out.println(type + " is stopping.");
    }
}

// Interface
interface Drivable {
    void drive();
}

// Subclass implementing both abstract class and interface
class Car extends Vehicle implements Drivable {
    Car(String type) {
        super(type);
    }

    @Override
    void start() {
        System.out.println(type + " is starting.");
    }

    @Override
    public void drive() {
        System.out.println(type + " is driving.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car("Car");
        car.start(); // Calls overridden method
        car.drive(); // Calls interface method
        car.stop();  // Calls inherited method
    }
}

6. Advantages of Abstract Classes and Interfaces

Abstract Classes:

  • Provide a common base class for subclasses.
  • Allow code reuse through concrete methods.
  • Support non-static and non-final fields.

Interfaces:

  • Define a contract for unrelated classes.
  • Support multiple inheritance.
  • Provide default and static methods (Java 8+).

Summary

ConceptDescription
Abstract ClassesProvide a common base class with abstract and concrete methods.
InterfacesDefine a contract with abstract, default, and static methods.
Abstract MethodsMethods without a body, must be implemented by subclasses.
Default MethodsMethods with a body in interfaces (Java 8+).
Static MethodsMethods with a body in interfaces (Java 8+).
Multiple InheritanceNot supported in abstract classes; supported in interfaces.

Understanding abstract classes and interfaces is essential for designing flexible and reusable Java applications. They are powerful tools for achieving abstraction and defining contracts in object-oriented programming.

Leave a Reply

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