The Wayback Machine - https://web.archive.org/web/20250305103712/https://www.geeksforgeeks.org/difference-between-abstract-class-and-interface-in-java/
Open In App

Difference between Abstract Class and Interface in Java

Last Updated : 04 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In object-oriented programming (OOP), both abstract classes and interfaces serve as fundamental constructs for defining contracts. They establish a blueprint for other classes, ensuring consistent implementation of methods and behaviors. However, they each come with distinct characteristics and use cases.

In this article, we will learn abstract class vs interface in Java.

Difference Between Abstract Class and Interface

Points

Abstract Class

Interface

Definition

Cannot be instantiated; contains both abstract (without implementation) and concrete methods (with implementation)

Specifies a set of methods a class must implement; methods are abstract by default.

Implementation Method

Can have both implemented and abstract methods.

Methods are abstract by default; Java 8, can have default and static methods.

Inheritance

class can inherit from only one abstract class.

A class can implement multiple interfaces.

Access Modifiers

Methods and properties can have any access modifier (public, protected, private).

Methods and properties are implicitly public.

Variables

Can have member variables (final, non-final, static, non-static).

Variables are implicitly public, static, and final (constants).

As we know that abstraction refers to hiding the internal implementation of the feature and only showing the functionality to the users. i.e. showing only the required features, and hiding how those features are implemented behind the scene. Whereas, an Interface is another way to achieve abstraction in java. Both abstract class and interface are used for abstraction, henceforth Interface and Abstract Class are required prerequisites.

Abstract Class vs Interface

Abstract Class in Java

1. Definition:

An abstract class is a class that cannot be instantiated directly. It serves as a blueprint for other classes to derive from.

2. Method Implementation:

An abstract class can contain both abstract methods (methods without an implementation) and concrete methods (methods with an implementation).

3. Variables:

Abstract classes can have member variables, including final, non-final, static, and non-static variables.

4. Constructors:

Abstract classes can have constructors, which can be used to initialize variables in the abstract class when it is instantiated by a subclass.

Example 1:

Java
abstract class Shape {
    String objectName = " ";

    Shape(String name) {
        this.objectName = name;
    }

    public void moveTo(int x, int y) {
        System.out.println(this.objectName + " has been moved to x = " + x + " and y = " + y);
    }

    abstract public double area();
    abstract public void draw();
}

class Rectangle extends Shape {
    int length, width;

    Rectangle(int length, int width, String name) {
        super(name);
        this.length = length;
        this.width = width;
    }

    @Override 
    public void draw() {
        System.out.println("Rectangle has been drawn ");
    }

    @Override 
    public double area() {
        return (double)(length * width);
    }
}

class Circle extends Shape {
    double pi = 3.14;
    int radius;

    Circle(int radius, String name) {
        super(name);
        this.radius = radius;
    }

    @Override 
    public void draw() {
        System.out.println("Circle has been drawn ");
    }

    @Override 
    public double area() {
        return (double)(pi * radius * radius);
    }
}

public class Main {
    public static void main(String[] args) {
        Shape rect = new Rectangle(2, 3, "Rectangle");
        System.out.println("Area of rectangle: " + rect.area());
        rect.moveTo(1, 2);

        System.out.println();

        Shape circle = new Circle(2, "Circle");
        System.out.println("Area of circle: " + circle.area());
        circle.moveTo(2, 4);
    }
}

Output
Area of rectangle: 6.0
Rectangle has been moved to x = 1 and y = 2

Area of circle: 12.56
Circle has been moved to x = 2 and y = 4

Example 2:

Java
// Abstract class Sunstar
abstract class Sunstar {
    // Abstract method printInfo
    abstract void printInfo();
}

// Employee class that extends the abstract class Sunstar
class Employee extends Sunstar {
    // Implementation of the abstract method printInfo
    void printInfo() {
        String name = "Avinash"; // Employee name
        int age = 21; // Employee age
        float salary = 222.2F; // Employee salary

        System.out.println(name); // Print name
        System.out.println(age); // Print age
        System.out.println(salary); // Print salary
    }
}

// Base class to test the implementation
class Base {
    public static void main(String args[]) {
        Sunstar s = new Employee(); // Create an Employee object
        s.printInfo(); // Call the printInfo method
    }
}

Output
Avinash
21
222.2

Interface in Java

1. Definition:

An interface is a reference type in Java, it is similar to a class, and it is a collection of abstract methods and static constants.

2. Method Implementation:

All methods in an interface are by default abstract and must be implemented by any class that implements the interface.From Java 8, interfaces can have default and static methods with concrete implementations.From Java 9, interfaces can also have private methods.

3. Variables:

Variables declared in an interface are by default public, static, and final (constants).

Example:

Java
interface Drawable {
    void draw();
}

interface Movable {
    void moveTo(int x, int y);
}

class Circle implements Drawable, Movable {
    double pi = 3.14;
    int radius;

    Circle(int radius) {
        this.radius = radius;
    }

    @Override 
    public void draw() {
        System.out.println("Circle has been drawn ");
    }

    @Override 
    public void moveTo(int x, int y) {
        System.out.println("Circle has been moved to x = " + x + " and y = " + y);
    }
}

public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle(2);
        circle.draw();
        circle.moveTo(2, 4);
    }
}

Output
Circle has been drawn 
Circle has been moved to x = 2 and y = 4

Abstract class vs Interface 

Points

Abstract Class

Interface

Type of Methods

Can have both abstract and concrete methods

Can have only abstract methods (until Java 7), and from Java 8, can have default and static methods, and from Java 9, can have private methods.

Variables

Can have final, non-final, static, and non-static variables.

Only static and final variables

Inheritance

Can extend only one class (abstract or not)

A class can implement multiple interfaces

Constructors

Can have constructors

Cannot have constructors

Implementation

Can provide the implementation of interface methods

Cannot provide the implementation of abstract class methods

By understanding these distinctions, you can make informed decisions about when to use abstract classes and interfaces in Java programming.

Features of an Abstract Class in Java

An abstract class in Java is a special type of class that cannot be instantiated directly and serves as a blueprint for other classes. It provides a way to define a common interface or behavior that can be shared by multiple related classes, but with specific implementations in each derived class.

Key features:

  • Cannot be instantiated: Abstract classes cannot be directly instantiated, meaning you cannot create objects of an abstract class.
  • Combining Partial Implementation and Subclass Contract: Abstract classes can contain abstract methods (methods without implementations) that must be overridden by subclasses. Additionally, they can have concrete methods with implementations, allowing abstract classes to provide both a partial implementation and a contract for subclasses to follow.
  • Can contain both abstract and non-abstract methods: Abstract classes can have both abstract and non-abstract methods. Non-abstract methods have complete implementations and can be called directly.
  • Can have constructors: Abstract classes can have constructors that can be called when a subclass is instantiated, allowing for initialization of the class’s fields.
  • Can have member variables: Abstract classes can have member variables, which are variables that belong to an instance of the class. These variables can be final, non-final, static, or non-static.
  • Can be used as a base class: Abstract classes can be used as a base class for other classes, meaning they can be inherited by other classes. This allows for code reuse and the creation of a common interface or behavior for related classes.

Overall, abstract classes in Java are used to define a common interface or behavior that can be shared by multiple related classes, with specific implementations provided by each derived class.

Features of an Interface in Java

An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields. The methods in interfaces are abstract by default (except for default and static methods introduced in Java 8 and private methods in Java 9). Here are the

Key features:

  • Defines a set of methods and properties: An interface defines a set of abstract methods that any class implementing the interface must provide implementations for. It acts as a contract that ensures certain methods are present in the implementing class. Interfaces can also declare constants (public static final variables).
  • Provides a common protocol: Interfaces establish a common protocol for different software components, allowing them to communicate with each other. This ensures consistency and interoperability across different parts of a software system.
  • Supports polymorphism: Interfaces support polymorphism, enabling objects of different classes to be treated as instances of the interface type. As long as the objects implement the same interface, they can be used interchangeably, promoting flexibility and extensibility.
  • Enables separation of concerns: By defining method signatures without implementations, interfaces promote separation of concerns. This allows different parts of a software system to be developed independently, as long as they adhere to the interface specifications. This decouples the implementation details from the interface.
  • Improves code reusability: Interfaces improve code reusability by allowing different classes to implement the same interface. This means that common functionality defined by the interface can be reused across multiple classes, reducing code duplication and enhancing maintainability.
  • Enforces design patterns: Interfaces can enforce design patterns, such as the Adapter pattern or Strategy pattern, by requiring certain methods or properties to be implemented by the implementing classes. This promotes consistent design and adherence to established best practices.
  • Facilitates testing: Interfaces facilitate testing by enabling the use of mock objects that implement the interface. This allows software components to be tested independently of each other, ensuring that each component behaves correctly in isolation before integrating them into the larger system.
  • Static and Default Methods: Since Java 8, interfaces can include default methods with implementations, which provide a way to add new methods to interfaces without breaking existing implementations. Interfaces can also include static methods, which belong to the interface itself rather than any instance.
  • Private Methods: Since Java 9, interfaces can also include private methods to encapsulate shared code between default methods, helping to avoid code duplication within the interface.

Overall, interfaces in Java are powerful tools for defining contracts and promoting flexibility, interoperability, and maintainability in software design.

When to use what?

Consider using abstract classes if any of these statements apply to your situation:  

  • In the Java application, there are some related classes that need to share some lines of code then you can put these lines of code within the abstract class and this abstract class should be extended by all these related classes.
  • You can define the non-static or non-final field(s) in the abstract class so that via a method you can access and modify the state of the object to which they belong.
  • You can expect that the classes that extend an abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).

Consider using interfaces if any of these statements apply to your situation:  

  • It is a total abstraction, all methods declared within an interface must be implemented by the class(es) that implements this interface.
  • A class can implement more than one interface. It is called multiple inheritances.
  • You want to specify the behavior of a data type without worrying about its implementation.

Summary

Abstract classes in Java serve as blueprints that cannot be instantiated directly and can include both abstract and concrete methods. They allow for partial implementation and can contain various types of member variables with any access modifier. A class can inherit only one abstract class. Interfaces, on the other hand, are contracts that specify a set of abstract methods that a class must implement, though they can include default and static methods from Java 8 onwards. Interfaces enable multiple inheritance of type, support polymorphism, and enforce a common protocol for different software components. Unlike abstract classes, all interface methods are implicitly public, and variables are public, static, and final.


Kickstart your Java journey with our online course on Java Programming, covering everything from basics to advanced concepts. Complete real-world coding challenges and gain hands-on experience. Join the Three 90 Challenge—finish 90% in 90 days for a 90% refund. Start mastering Java today!


Next Article

Similar Reads

Difference Between Abstract Class and Abstract Method in Java
Abstract is the modifier applicable only for methods and classes but not for variables. Even though we don't have implementation still we can declare a method with an abstract modifier. That is abstract methods have only declaration but not implementation. Hence, abstract method declaration should compulsory ends with semicolons. Illustration: pu
3 min read
Implement Interface using Abstract Class in Java
Interface contains only abstract methods that can't be instantiated and it is declared by keyword interface. A class that is declared with the abstract keyword is known as an abstract class in Java. This is a class that usually contains at least one abstract method which can't be instantiated and It is also possible for the class to have no methods
3 min read
Are All Methods in a Java Interface are Abstract?
In Java, the interface is called a blueprint of a class and it is used to achieve abstraction in java. By using interfaces only we can achieve multiple inheritances in java. Let's understand the concept of blueprint through an example like a blueprint of the building will consist of properties and behaviors of the building but for every building, i
8 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Why to Use Comparator Interface Rather than Comparable Interface in Java?
In Java, the Comparable and Comparator interfaces are used to sort collections of objects based on certain criteria. The Comparable interface is used to define the natural ordering of an object, whereas the Comparator interface is used to define custom ordering criteria for an object.Here are some reasons why you might want to use the Comparator in
8 min read
Difference between Final and Abstract in Java
In this article, the difference between the abstract class and the final class is discussed. Before getting into the differences, lets first understand what each of this means. Final Class: A class which is declared with the "Final" keyword is known as the final class. The final keyword is used to finalize the implementations of the classes, the m
4 min read
Abstract Class in Java
In Java, abstract class is declared with the abstract keyword. It may have both abstract and non-abstract methods(methods with bodies). An abstract is a Java modifier applicable for classes and methods in Java but not for Variables. In this article, we will learn the use of abstract classes in Java.What is Abstract Class in Java?Java abstract class
10 min read
Can We Instantiate an Abstract Class in Java?
Abstract class, we have heard that abstract class are classes which can have abstract methods and it can't be instantiated. We cannot instantiate an abstract class in Java because it is abstract, it is not complete, hence it cannot be used.Example 1Java// Java program to demonstrate abstract class // cannot have instance public abstract class Class
3 min read
Constructor in Java Abstract Class
Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor. So if we do not define any constructor inside the abstract class then JVM (Java Virtual Machine) will give a default constructor to the abstract class. I
4 min read
Difference Between ReadWriteLock Interface and ReentrantReadWriteLock Class in Java
ReadWriteLock is an interface in java. A ReadWriteLock allows us to add a thread-safety feature to a data structure while increasing throughput by allowing multiple threads to read the data concurrently and one thread to update the data exclusively. ReadWriteLock is described in the java.util.concurrent.locks package, with ReentrantReadWriteLock i
3 min read