Table of contents
1.
Introduction
2.
Difference Between Abstract Class and Interface
3.
Abstract Class in Java
4.
Interface in Java
5.
Abstract class vs Interface
6.
Features of an Abstract Class in Java
7.
Features of an Interface in Java
8.
When to use what?
9.
Use an interface when
10.
Use Abstract classes and Interface both
11.
Frequently Asked Questions
11.1.
Can an abstract class implement an interface?
11.2.
Can an interface extend another interface?
11.3.
Can an abstract class have non-abstract methods?
12.
Conclusion
Last Updated: Nov 3, 2024
Easy

Difference between Abstract Class and Interface in Java

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, abstract classes & interfaces are two essential tools that allow developers to define common structures & behaviors for objects. They act like a blueprint, which provides a foundation for other classes to build upon. Abstract classes are classes that cannot be instantiated directly, which means you cannot create objects from them. They may contain a mix of abstract methods (methods without a body) & concrete methods (methods with an implementation). On the other hand, interfaces are purely abstract and contain only abstract methods. They define a contract that classes can implement, ensuring they adhere to a specific set of methods. 

Difference between Abstract Class and Interface in Java

In this article, we will understand the characteristics of abstract classes & interfaces, discuss their unique features, & learn when to use each one. We will also see code examples to understand their use cases and implementation.

Difference Between Abstract Class and Interface

Abstract classes and interfaces are both used for abstraction in Java, but they differ in several ways. An abstract class is a class that cannot be instantiated and may contain abstract methods, non-abstract methods, and constructors. It can also have instance variables and static variables. Abstract classes are declared using the "abstract" keyword and can be extended by other classes using the "extends" keyword. A class can extend only one abstract class.


On the other hand, an interface is a completely abstract type that contains only abstract methods and constant variables. It does not have a constructor and cannot be instantiated. An interface is declared using the "interface" keyword and can be implemented by classes using the "implements" keyword. A class can implement multiple interfaces, allowing for multiple inheritance of type.


Another significant difference is that abstract classes can provide a partial implementation for methods, while interfaces cannot. Abstract classes can have non-abstract methods with a body, but all methods in an interface are implicitly abstract & public.


This example will show the difference between these two : 

// Abstract class
abstract class Animal {
   protected String name;
   
   public Animal(String name) {
      this.name = name;
   }
   
   public abstract void makeSound();
}


// Interface
interface Flyable {
   void fly();
}


// Concrete class extending abstract class & implementing interface
class Bird extends Animal implements Flyable {
   public Bird(String name) {
      super(name);
   }
   
   @Override
   public void makeSound() {
      System.out.println("Chirp!");
   }
   
   @Override
   public void fly() {
      System.out.println("Flying high!");
   }
}


In this example, the `Animal` class is an abstract class with a constructor, an instance variable `name`, and an abstract method `makeSound()`. The `Flyable` interface declares an abstract method, `fly()`. The `Bird` class extends the `Animal` abstract class and implements the `Flyable` interface, providing implementations for both the `makeSound()` and `fly()` methods.

Abstract Class in Java

An abstract class in Java is a class that cannot be instantiated on its own. It serves as a base from which other classes can inherit. Abstract classes are declared using the `abstract` keyword. They can contain both abstract methods (methods without a body) & concrete methods (methods with an implementation).

Here are some key points about abstract classes in Java:

- Abstract classes are declared using the `abstract` keyword before the class definition.
 

- Abstract classes can have constructors, which are called when an instance of a concrete subclass is created.
 

- Abstract classes can contain fields (instance variables) & concrete methods with implementation.
 

- Abstract classes can also contain abstract methods, which are declared without a body and must be implemented by the subclasses.
 

- A class that extends an abstract class must implement all the abstract methods defined in the abstract class unless it is also an abstract class.
 

- Abstract classes can have access modifiers such as public, protected, & private.
 

- Abstract classes can be used to provide common functionality & define a base structure for subclasses.


For example : 

public abstract class Shape {
    protected String color;
    
    public Shape(String color) {
        this.color = color;
    }
    
    public abstract double getArea();
    
    public void displayColor() {
        System.out.println("Color: " + color);
    }
}


In this example, the `Shape` class is declared an abstract class. It has a constructor that takes a `color` parameter, an abstract method `getArea()` that must be implemented by subclasses, and a concrete method `displayColor()` that prints the shape's color.

Subclasses can extend the `Shape` class & provide implementations for the abstract methods, like this:

public class Circle extends Shape {
    private double radius;
    
    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }
    
    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }
}


The `Circle` class extends the `Shape` class, provides a constructor that calls the superclass constructor, & implements the `getArea()` method specific to a circle.

Note: Abstract classes allow for code reuse and provide a way to define common behavior that subclasses can inherit and extend.

Interface in Java

An interface in Java is a blueprint of a class that contains only abstract methods. It is a collection of abstract methods and constant fields. Interfaces are declared using the `interface` keyword. They provide a way to achieve abstraction and define a contract that classes must follow.

some important points about interfaces in Java are mentioned below:

- Interfaces are declared using the `interface` keyword.
 

- Interfaces can only contain abstract methods, which are methods without a body.
 

- All methods in an interface are implicitly public & abstract, so you don't need to explicitly specify the `public` & `abstract` keywords.
 

- Interfaces can also contain constant fields, which are implicitly `public`, `static`, & `final`.
 

- A class can implement multiple interfaces using the `implements` keyword, separating each interface with a comma.
 

- A class that implements an interface must provide implementations for all the methods declared in the interface.
 

- Interfaces can extend other interfaces using the `extends` keyword, allowing for interface inheritance.
 

- Starting from Java 8, interfaces can have default methods & static methods with implementation.
 

For example : 

public interface Drawable {
    void draw();
    
    default void erase() {
        System.out.println("Erasing the drawing.");
    }
    
    static void displayInfo() {
        System.out.println("This is a drawable interface.");
    }
}

 

In this example, the `Drawable` interface declares an abstract method `draw()`, a default method `erase()`, & a static method `displayInfo()`. Any class that implements the `Drawable` interface must provide an implementation for the `draw()` method.

Classes can implement interfaces like this:

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


The `Circle` class implements the `Drawable` interface & provides an implementation for the `draw()` method.


Note: Interfaces allow for multiple inheritance, as a class can implement multiple interfaces. They also provide a way to define a contract that classes must follow, enabling loose coupling and promoting code reusability.

Abstract class vs Interface

AspectAbstract ClassInterface
DefinitionA class that cannot be instantiated and may contain both abstract and non-abstract methods.A completely abstract type that contains only abstract methods and constants.
InheritanceA class can extend only one abstract class using the extends keyword.A class can implement multiple interfaces using the implements keyword.
ConstructorsCan have constructors, which are called when an instance of a concrete subclass is created.Cannot have constructors since they cannot be instantiated directly.
Fields & MethodsCan have fields (instance variables) and concrete methods with implementation.Cannot have fields (except for constants) and cannot provide method implementations until Java 8.
Access ModifiersCan define access modifiers such as public, protected, and private for their members.All methods are implicitly public and abstract, and all fields are implicitly public, static, and final.
PurposeUsed to define a common base for subclasses and provide default implementations for methods.Defines a contract that implementing classes must follow and does not provide any implementation until Java 8.
Use CaseUsed when there is a need for a base class with some common functionality.Used to define a common behavior that unrelated classes can implement.
Examplepublic abstract class Animal { ... }public interface Flyable { ... }

Features of an Abstract Class in Java

1. An abstract class is declared using the `abstract` keyword before the class definition.
 

2. An abstract class can contain both abstract and non-abstract methods. Abstract methods are declared without a body and must be implemented by the subclasses.
 

3. An abstract class can have constructors, which are called when an instance of a concrete subclass is created. The constructors of an abstract class are used to initialize the fields of the abstract class.
 

4. An abstract class can have fields (instance variables) that can be accessed by the subclasses. These fields can have different access modifiers such as public, protected, or private.
 

5. An abstract class can provide default implementations for methods, which can be overridden by the subclasses if needed. This allows for code reuse and provides a way to define common behavior for subclasses.
 

6. An abstract class can have static methods, which can be called directly on the abstract class itself without creating an instance of the class.
 

7. An abstract class can be extended by another abstract class or a concrete class using the `extends` keyword. However, a class can only extend one abstract class.
 

8. An abstract class can implement interfaces, providing implementations for the methods declared in the interfaces.
 

9. An abstract class can be used to define a template for subclasses, enforcing a certain structure and behavior.

Features of an Interface in Java

1. An interface is declared using the `interface` keyword.
 

2. An interface can only contain abstract methods, which are methods without a body. The classes that implement the interface must implement these methods.
 

3. All methods in an interface are implicitly public and abstract, so you don't need to explicitly specify the `public` and `abstract` keywords.
 

4. An interface can also contain constant fields, which are implicitly `public`, `static`, and `final`. These fields must be initialized at the time of declaration.
 

5. An interface cannot have constructors since it cannot be instantiated directly.
 

6. An interface can extend other interfaces using the `extends` keyword, allowing for interface inheritance. A class can implement multiple interfaces, providing implementations for all the methods declared in the interfaces.
 

7. Starting from Java 8, interfaces can have default methods, which provide a default implementation for the methods. Classes implementing the interface can choose to override the default methods if needed.
 

8. Also, starting from Java 8, interfaces can have static methods, which can be called directly on the interface itself without requiring an instance of a class that implements the interface.
 

9. Interfaces are used to define a contract or common behavior that classes must adhere to. They provide a way to achieve abstraction and promote loose coupling between classes.

When to use what?

Deciding whether to use an abstract class or an interface depends on the specific requirements and design of your system. Here are some guidelines to help you make the decision:

Use an abstract class when:

1. You want to provide a common base implementation for subclasses to inherit from. Abstract classes can contain fields and non-abstract methods with implementation, allowing subclasses to reuse and extend the behavior.
 

2. You have a class that needs to be extended by subclasses, and you want to enforce a certain structure and behavior. Abstract classes can define a template for subclasses to follow.
 

3. You need to define a common interface for closely related classes. Abstract classes can be used to group related classes under a common type.
 

4. You want to share code among closely related classes. Abstract classes can contain common code that can be inherited by subclasses, promoting code reuse.
 

Example scenario: Consider a banking system where you have different types of accounts (e.g., SavingsAccount, CheckingAccount). You can define an abstract `Account` class that contains common fields (e.g., accountNumber, balance) and methods (e.g., deposit(), withdraw()). The subclasses can inherit from the `Account` class and provide their specific implementations.

Use an interface when

1. You want to define a contract for unrelated classes to follow. Interfaces provide a way to specify a common behavior that classes from different hierarchies can implement.
 

2. You need to achieve multiple inheritance. Since Java does not support multiple inheritance for classes, interfaces can be used to achieve a form of multiple inheritance. A class can implement multiple interfaces.
 

3. You want to define a common behavior that can be implemented by different classes without sharing a common base class. Interfaces allow classes to have a common behavior without being related by inheritance.
 

4. You want to provide a way for using objects interchangeably based on their behavior. Interfaces define a contract that objects can adhere to, allowing them to be used polymorphically.


Note: In summary, use abstract classes when you want to provide a common base implementation and define a template for subclasses, and use interfaces when you want to define a contract for unrelated classes to follow and achieve a form of multiple inheritance.

Use Abstract classes and Interface both

In some cases, abstract classes and interfaces can be combined to achieve a more flexible and modular design. With the combination of both abstract classes and interfaces, you can define a common structure and behavior while also allowing for multiple inheritance and loose coupling.

Let’s look at a few possible scenarios where both abstract classes and interfaces can be useful:
 

1. Defining a common base class and a contract for specific behavior:

   - You can define an abstract class that provides common fields and methods for inheriting subclasses.
 

   - Additionally, you can define an interface that specifies a contract for specific behavior that the subclasses must implement.
 

   Subclasses can extend the abstract class and implement the interface, inheriting the common behavior from the abstract class and providing their own implementations for the methods defined in the interface.
 

   Example:

   public abstract class Animal {
       protected String name;
       
       public Animal(String name) {
           this.name = name;
       }
       
       public abstract void eat();
   }
   
   public interface Swimmable {
       void swim();
   }
   
   public class Fish extends Animal implements Swimmable {
       public Fish(String name) {
           super(name);
       }
       
       @Override
       public void eat() {
           System.out.println(name + " is eating.");
       }
       
       @Override
       public void swim() {
           System.out.println(name + " is swimming.");
       }
   }


2. Achieving multiple inheritance:

   - Java does not support multiple inheritance for classes, but a class can implement multiple interfaces.

   - You can define an abstract class with common functionality and multiple interfaces that define different contracts.

   Subclasses can extend the abstract class and implement the necessary interfaces, inheriting the common behavior from the abstract class and providing implementations for the methods defined in the interfaces.
 

   Example:

   public abstract class Shape {
       protected String color;
       
       public Shape(String color) {
           this.color = color;
       }
       
       public abstract double getArea();
   }
   
   public interface Resizable {
       void resize(double factor);
   }
   
   public interface Movable {
       void move(double dx, double dy);
   }
   
   public class Rectangle extends Shape implements Resizable, Movable {
       private double width;
       private double height;
       
       public Rectangle(String color, double width, double height) {
           super(color);
           this.width = width;
           this.height = height;
       }
       
       @Override
       public double getArea() {
           return width * height;
       }
       
       @Override
       public void resize(double factor) {
           width *= factor;
           height *= factor;
       }
       
       @Override
       public void move(double dx, double dy) {
           // Implementation for moving the rectangle
       }
   }


By combining abstract classes and interfaces, you can create a more modular and flexible design that allows for code reuse, multiple inheritance, and loose coupling between classes.

Frequently Asked Questions

Can an abstract class implement an interface?

Yes, an abstract class can implement one or more interfaces. It can provide implementations for some or all of the methods declared in the interfaces.

Can an interface extend another interface?

Yes, an interface can extend one or more interfaces using the `extends` keyword. This allows for interface inheritance and creating a hierarchy of interfaces.

Can an abstract class have non-abstract methods?

Yes, an abstract class can have both abstract and non-abstract methods. Non-abstract methods in an abstract class provide a default implementation that can be inherited by subclasses.

Conclusion

In this article, we discussed the differences between abstract classes and interfaces in Java. We learned that abstract classes provide a common base for subclasses and can contain both abstract and non-abstract methods. At the same time, interfaces define a contract for unrelated classes to follow and contain only abstract methods. We also discussed the features of abstract classes and interfaces, when to use each one, and how they can be used together to create a more modular and flexible design. 

You can also check out our other blogs on Code360.

Live masterclass