DEV Community

Cover image for Interfaces and Abstract Classes in Java
Dhanush
Dhanush

Posted on

Interfaces and Abstract Classes in Java

Interfaces and abstract classes are the essential components for achieving abstraction and polymorphism.

What are Interfaces?

An interface in Java is a reference type, similar to a class, that can contain only abstract methods, static methods, default methods, and static final variables (constants). Interfaces are used to achieve abstraction and multiple inheritance in Java. Interfaces may not be directly instantiated.

Keep Coding

👉Before Java 8, interfaces could have only abstract methods.
The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided in the class implementing the same interface.

👉To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.

Default methods can be overridden by implementing classes if necessary.

Key Features of Interfaces

  • Abstract Methods: Methods without a body, declared using the abstract keyword.
  • Default Methods: Methods with a body, introduced in Java 8, allowing interfaces to provide default implementations.
  • Static Methods: Methods that belong to the interface itself, not to instances of the interface.
  • Constants: Variables declared as static and final, which are implicitly public.

What are Abstract Classes?

An abstract class in Java is a class that cannot be instantiated on its own and may contain abstract methods (methods without a body) and concrete methods (methods with a body). Abstract classes are used to provide a common base for subclasses, allowing for code reuse and the definition of shared behavior.

Key Features of Abstract Classes

  • Abstract Methods: Methods without a body, declared using the abstract keyword.
  • Concrete Methods: Methods with a body, providing default implementations.
  • Constructors: Abstract classes can have constructors, but they cannot be instantiated directly.
  • Instance Variables: Abstract classes can have instance variables and static variables.

Differences Between Interfaces and Abstract Classes

Multiple Inheritance

  • Interfaces: Java supports multiple inheritance through interfaces, allowing a class to implement multiple interfaces.
  • Abstract Classes: Java does not support multiple inheritance of classes, meaning a class can extend only one abstract class.

Method Bodies

  • Interfaces: Prior to Java 8, interfaces could not contain method bodies. With Java 8, default and static methods can have bodies.
  • Abstract Classes: Abstract classes can contain both abstract methods (without bodies) and concrete methods (with bodies).

Variables

  • Interfaces: Variables in interfaces are implicitly public, static, and final.
  • Abstract Classes: Abstract classes can have instance variables, static variables, and constants.

Usage

  • Interfaces: Ideal for defining contracts that multiple classes can implement.
  • Abstract Classes: Suitable for providing a common base for a family of related classes, sharing code and behavior.

Java's Approach to Inheritance

Java supports only single inheritance, meaning each class can inherit fields and methods of only one class. If you need to inherit properties from more than one source, Java provides the concept of interfaces, which is a form of multiple inheritance.

👉Interfaces are similar to classes. However, they define only the signature of the methods and not their implementations. The methods that are declared in the interface are implemented in the classes. Multiple inheritance occurs when a class implements multiple interfaces.

In Java, multiple inheritance is achieved through interfaces rather than classes. This allows a class to implement multiple interfaces, inheriting the method signatures from each of them. Below is an example demonstrating multiple inheritance using interfaces.

Example of Multiple Inheritance Using Interfaces

Let's define two interfaces, Flyable and Swimmable, and a class Duck that implements both interfaces.

Interface: Flyable

public interface Flyable {
    void fly();
}
Enter fullscreen mode Exit fullscreen mode

Interface: Swimmable

public interface Swimmable {
    void swim();
}
Enter fullscreen mode Exit fullscreen mode

Class: Duck

public class Duck implements Flyable, Swimmable {
    @Override
    public void fly() {
        System.out.println("Duck is flying");
    }

    @Override
    public void swim() {
        System.out.println("Duck is swimming");
    }

    public static void main(String[] args) {
        Duck duck = new Duck();
        duck.fly();
        duck.swim();
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. Interfaces:

    • Flyable interface defines a method fly().
    • Swimmable interface defines a method swim().
  2. Class:

    • Duck class implements both Flyable and Swimmable interfaces.
    • The Duck class provides implementations for both fly() and swim() methods.
  3. Main Method:

    • An instance of Duck is created.
    • The fly() and swim() methods are called on the Duck instance, demonstrating that the Duck class has inherited behavior from both interfaces.

Output

Duck is flying
Duck is swimming
Enter fullscreen mode Exit fullscreen mode

Here's a simple diagram to illustrate the relationship:

+----------------+
|    Flyable     |<--------------->Interface
|----------------|
| + fly()        |
+----------------+
          ^
          |
          | Implements
          |
+----------------+
|     Duck       |<--------------->Class
|----------------|
| + fly()        |
| + swim()       |
+----------------+
          ^
          |
          | Implements
          |
+----------------+
|   Swimmable    |<--------------->Interface
|----------------|
| + swim()       |
+----------------+
Enter fullscreen mode Exit fullscreen mode

In this example, the Duck class demonstrates multiple inheritance by implementing both the Flyable and Swimmable interfaces. This allows the Duck class to inherit and provide implementations for the methods defined in both interfaces, showcasing how Java achieves multiple inheritance through interfaces.


Abstract Class in Java

Abstract classes in Java are used to provide a common base for a family of related classes. They can contain both abstract methods (methods without a body) and concrete methods (methods with a body). Below is an example demonstrating the use of an abstract class.

Example of an Abstract Class

Let's define an abstract class Animal and two subclasses Dog and Cat that extend the Animal class.

Abstract Class: Animal

public abstract class Animal {
    // Abstract method (does not have a body)
    public abstract void makeSound();

    // Concrete method (has a body)
    public void sleep() {
        System.out.println("The animal is sleeping");
    }
}
Enter fullscreen mode Exit fullscreen mode

Subclass: Dog

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog says: Woof!");
    }

    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.makeSound();
        dog.sleep();
    }
}
Enter fullscreen mode Exit fullscreen mode

Subclass: Cat

public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Cat says: Meow!");
    }

    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.makeSound();
        cat.sleep();
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. Abstract Class: Animal

    • The Animal class is declared as abstract, meaning it cannot be instantiated directly.
    • It contains an abstract method makeSound(), which must be implemented by any subclass.
    • It also contains a concrete method sleep(), which provides a default implementation.
  2. Subclass: Dog

    • The Dog class extends the Animal class.
    • It provides an implementation for the abstract method makeSound().
    • The main method creates an instance of Dog and calls the makeSound() and sleep() methods.
  3. Subclass: Cat

    • The Cat class extends the Animal class.
    • It provides an implementation for the abstract method makeSound().
    • The main method creates an instance of Cat and calls the makeSound() and sleep() methods.

Output

For the Dog class:

Dog says: Woof!
The animal is sleeping
Enter fullscreen mode Exit fullscreen mode

For the Cat class:

Cat says: Meow!
The animal is sleeping
Enter fullscreen mode Exit fullscreen mode

Here's a simple diagram to illustrate the relationship:

+----------------+
|    Animal      |
|----------------|
| + makeSound()  |<-----------+
| + sleep()      |            |
+----------------+            |
          ^                   | Extends
          |                   |
          | Extends           |
          |                   |
+----------------+     +----------------+
|     Dog(class) |     |     Cat(class) |
|----------------|     |----------------|
| + makeSound()  |     | + makeSound()  |
+----------------+     +----------------+
Enter fullscreen mode Exit fullscreen mode

In this example, the Animal abstract class provides a common base for the Dog and Cat subclasses. The Animal class defines an abstract method makeSound() that must be implemented by any subclass, and a concrete method sleep() that provides a default implementation. The Dog and Cat classes extend the Animal class and provide their own implementations of the makeSound() method.

Key Points About Interfaces

  1. Abstraction: The interface in Java is a mechanism to achieve abstraction.
  2. Default Methods: By default, interface methods are abstract and public.
  3. Method Types: Interface methods can be only public, private, abstract, default, static, and strictfp.
  4. Field Types: Interface fields (variables) can be only public, static, or final.
  5. IS-A Relationship: Java Interface also represents the IS-A relationship.
  6. Instantiation: It cannot be directly instantiated, just like the abstract class.
  7. Loose Coupling: It can be used to achieve loose coupling.
  8. Implicitly Abstract: Every interface is implicitly abstract.
  9. Default Methods: default methods are allowed only in interfaces.
interface Colorable {
    void setColor(byte r, byte g, byte b);
}

class Point { int x, y; }

class ColoredPoint extends Point implements Colorable {
    byte r, g, b;
    public void setColor(byte rv, byte gv, byte bv) {
        r = rv; g = gv; b = bv;
    }
}

class Test {
    public static void main(String[] args) {
        Point p = new Point();
        ColoredPoint cp = new ColoredPoint();
        p = cp;
        Colorable c = cp; 
        // interface object assigned indirectly
    }
}
Enter fullscreen mode Exit fullscreen mode

Practical Applications

Using Interfaces

Interfaces are commonly used to define APIs, frameworks, and libraries. For example, the java.util.List interface provides a contract for list implementations, such as ArrayList and LinkedList.

public interface List<E> extends Collection<E> {
    boolean add(E e);
    E get(int index);
    // Other methods...
}
Enter fullscreen mode Exit fullscreen mode

Using Abstract Classes

Abstract classes are often used to provide a base class for a family of related classes. For example, the java.util.AbstractList class provides a skeletal implementation of the List interface, reducing the amount of code that subclasses need to implement.

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    protected AbstractList() {}
    public boolean add(E e) {
        add(size(), e);
        return true;
    }
    // Other methods...
}
Enter fullscreen mode Exit fullscreen mode

Difference Between Interface and Abstract class

SNo Interface Abstract Class
1 Interfaces cannot be instantiated Abstract classes cannot be instantiated
2 It can have both abstract and non-abstract methods It can have both abstract and non-abstract methods
3 In interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public In abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods
4 Interface supports multiple inheritance. Multiple interfaces can be implemented Abstract class or class can extend only one class
5 It is used if you expect that unrelated classes would implement your interface. Eg, the interfaces Comparable and Cloneable are implemented by many unrelated classes It is used if you want to share code among several closely related classes
6 It is used if you want to specify the behavior of a particular data type, but not concerned about who implements its behavior. It is used if you expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private)

Ref: https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.


Expert Opinions

According to Joshua Bloch, author of "Effective Java," interfaces are preferred over abstract classes for defining types because they are more flexible and support multiple inheritance. However, abstract classes are useful for providing shared functionality and reducing code duplication.

"Interfaces are ideal for defining mixins. Classes, by contrast, are ideal for defining objects that have intrinsic properties."

  • Joshua Bloch

Highlights

  • Interfaces: Ideal for defining contracts and supporting multiple inheritance.
  • Abstract Classes: Suitable for providing a common base for related classes, sharing code and behavior.
  • Differences: Interfaces can have only abstract methods (prior to Java 8), while abstract classes can have both abstract and concrete methods.
  • Usage: Interfaces are used for defining APIs and frameworks, while abstract classes are used for providing skeletal implementations.

Explore Further

Explore the power of interfaces and abstract classes in your own Java projects. Experiment with defining contracts using interfaces and providing shared functionality using abstract classes. Share your insights and experiences with the Java community to contribute to the collective knowledge and growth.

Any corrections or additions to this post are welcome.

                          Happy coding!😎
Enter fullscreen mode Exit fullscreen mode

Top comments (0)