The Wayback Machine - https://web.archive.org/web/20240603234521/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 : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Abstract class and interface are both used to define contracts in object-oriented programming, but there are some key differences between them.

Difference between abstract class and interface:-

Definition: An abstract class is a class that cannot be instantiated and can contain both abstract and non-abstract methods. An interface, on the other hand, is a contract that specifies a set of methods that a class must implement.

Method implementation: In an abstract class, some methods can be implemented, while others are left abstract, meaning that they have no implementation and must be overridden by concrete subclasses. In contrast, all methods in an interface are by default abstract and must be implemented by any class that implements the interface.

Inheritance: A class can inherit from only one abstract class, but it can implement multiple interfaces. This is because an abstract class represents a type of object, while an interface represents a set of behaviors.

Access modifiers: Abstract classes can have access modifiers such as public, protected, and private for their methods and properties, while interfaces can only have public access.

Variables: An abstract class can have member variables, while an interface cannot.

In summary, abstract classes are used to provide a base class for concrete subclasses to inherit from, while interfaces are used to define a set of methods that a class must implement. Abstract classes can have implemented and abstract methods, while interfaces can only have abstract methods. Classes can inherit from only one abstract class, but can implement multiple interfaces.

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 vs Interface 

  • Type of methods: Interface can have only abstract methods. Whereas, an abstract class can have abstract method and concrete methods. From Java 8, it can have default and static methods also. From Java 9, it can have private concrete methods as well. 
  • Note : Concrete methods are those methods which has their complete definition but they can also be overriden in the inherited class. However, if we make the concrete method as “FINAL” it cannot be overrided in the inherited class because declaring a method as final means  – its implementation is complete.
  • Final Variables: Variables declared in a Java interface are by default final. An abstract class can contain non-final variables.
  • Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables.
  • Implementation: Abstract class can provide the implementation of the interface. Interface can’t provide the implementation of an abstract class.
  • Inheritance vs Abstraction: A Java interface can be implemented using the keyword “implements” and an abstract class can be extended using the keyword “extends”.
  • Multiple implementations: An interface can extend one or more Java interfaces; an abstract class can extend another Java class and implement multiple Java interfaces.
  • Multiple Inheritance:  Multiple inheritance can be partially achieved by the use of interfaces , whereas the same can’t be done by the use of abstract classes. Because in Java, one class can implement multiple Interfaces, but one class cannot extend from multiple other classes because that’s just not possible in java as that would lead to the diamond problem. 
  • Accessibility of Data Members: Members(variables) of a Java interface are final by default. A Java abstract class can have class members like private, protected, etc.

Features of abstract class:-

An abstract class is a special type of class in object-oriented programming that cannot be instantiated directly. Instead, it serves as a blueprint or template for other classes to be derived from. An abstract class:

  1. Cannot be instantiated: Abstract classes cannot be directly instantiated, which means you cannot create objects of an abstract class.
  2. Contains at least one pure virtual function: Abstract classes must contain at least one pure virtual function, which means that the function has no implementation and must be implemented by any derived classes.
  3. Can contain both abstract and non-abstract methods: Abstract classes can have both abstract and non-abstract methods. Non-abstract methods have a complete implementation and can be called directly.
  4. Can have constructors and destructors: Abstract classes can have constructors and destructors like any other class.
  5. Can have member variables: Abstract classes can have member variables, which are variables that belong to an object of the class.
  6. Can be used as a base class: Abstract classes can be used as a base class for other classes, which means that they can be inherited by other classes.

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

Example 1 :  (For Abstract Class )

Java
abstract class sunstar {
  
    abstract void printInfo();
}

class employee extends sunstar {
    void printInfo()
    {
        String name = "avinash";
        int age = 21;
        float salary = 222.2F;

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

class base {
    public static void main(String args[])
    {
        sunstar s = new employee();
        s.printInfo();
    }
}

Output
avinash
21
222.2

Example 2 :  (For Abstract Class )

Java
// Java Program to Illustrate Concept of
// Abstract Class

// Importing required classes
import java.io.*;

// Class 1
// Helper abstract class
abstract class Shape {

    // Declare fields
    String objectName = " ";

    // Constructor of this class
    Shape(String name) { this.objectName = name; }

    // Method
    // Non-abstract methods
    // Having as default implementation
    public void moveTo(int x, int y)
    {
        System.out.println(this.objectName + " "
                           + "has been moved to"
                           + " x = " + x + " and y = " + y);
    }

    // Method 2
    // Abstract methods which will be
    // implemented by its subclass(es)
    abstract public double area();
    abstract public void draw();
}

// Class 2
// Helper class extending Class 1
class Rectangle extends Shape {

    // Attributes of rectangle
    int length, width;

    // Constructor
    Rectangle(int length, int width, String name)
    {

        // Super keyword refers to current instance itself
        super(name);

        // this keyword refers to current instance itself
        this.length = length;
        this.width = width;
    }

    // Method 1
    // To draw rectangle
    @Override public void draw()
    {
        System.out.println("Rectangle has been drawn ");
    }

    // Method 2
    // To compute rectangle area
    @Override public double area()
    {
        // Length * Breadth
        return (double)(length * width);
    }
}

// Class 3
// Helper class extending Class 1
class Circle extends Shape {

    // Attributes of a Circle
    double pi = 3.14;
    int radius;

    // Constructor
    Circle(int radius, String name)
    {
        // Super keyword refers to parent class
        super(name);
        // This keyword refers to current instance itself
        this.radius = radius;
    }

    // Method 1
    // To draw circle
    @Override public void draw()
    {
        // Print statement
        System.out.println("Circle has been drawn ");
    }

    // Method 2
    // To compute circle area
    @Override public double area()
    {
        return (double)((pi * radius * radius));
    }
}

// Class 4
// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating the Object of Rectangle class
        // and using shape class reference.
        Shape rect = new Rectangle(2, 3, "Rectangle");

        System.out.println("Area of rectangle: "
                           + rect.area());

        rect.moveTo(1, 2);

        System.out.println(" ");

        // Creating the Objects of circle class
        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

What if we don’t have any common code between rectangle and circle then go with the interface. 

Interface: 

Features of interface:

An interface:

  1. Defines a set of methods and properties: An interface defines a set of methods and properties that must be implemented by any class or structure that implements the interface.
  2. Provides a common protocol: Interfaces provide a common protocol that allows different software components to communicate with each other.
  3. Supports polymorphism: An interface can be used to achieve polymorphism, which means that objects of different classes can be treated as if they belong to the same type, as long as they implement the same interface.
  4. Enables separation of concerns: Interfaces enable separation of concerns, which means that different parts of a software system can be developed independently of each other, as long as they adhere to the interface specifications.
  5. Improves code reusability: Interfaces improve code reusability by allowing different software components to reuse the same code base, as long as they implement the same interface.
  6. Enforces design patterns: Interfaces can be used to enforce design patterns, such as the Adapter pattern, by requiring that certain methods or properties be implemented by the implementing classes.
  7. Facilitates testing: Interfaces facilitate testing by allowing software components to be tested independently of each other, using mock objects that implement the interface.

Example 1: For Interface

Java
// Java Program to Illustrate Concept of Interface

// Importing I/O classes
import java.io.*;

// Interface
interface Shape {

    // Abstract method
    void draw();
    double area();
}

// Class 1
// Helper class
class Rectangle implements Shape {

    int length, width;

    // constructor
    Rectangle(int length, int width)
    {
        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 2
// Helper class
class Circle implements Shape {

    double pi = 3.14;
    int radius;

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

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

    @Override public double area()
    {

        return (double)((pi * radius * radius));
    }
}

// Class 3
// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating the Object of Rectangle class
        // and using shape interface reference.
        Shape rect = new Rectangle(2, 3);

        System.out.println("Area of rectangle: "
                           + rect.area());

        // Creating the Objects of circle class
        Shape circle = new Circle(2);

        System.out.println("Area of circle: "
                           + circle.area());
    }
}

Output
Area of rectangle: 6.0
Area of circle: 12.56

Example 2: For  Interface 

Java
// Java Program to Illustrate Concept of Interface

// Importing I/O classes
import java.io.*;

// Interface
interface Shape {

    // Abstract method
    void draw();
    double area();
}

// Class 1
// Helper class
class Rectangle implements Shape {

    int length, width;

    // constructor
    Rectangle(int length, int width)
    {
        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 2
// Helper class
class Circle implements Shape {

    double pi = 3.14;
    int radius;

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

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

    @Override public double area()
    {

        return (double)((pi * radius * radius));
    }
}

// Class 3
// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating the Object of Rectangle class
        // and using shape interface reference.
        Shape rect = new Rectangle(2, 3);

        System.out.println("Area of rectangle: "
                           + rect.area());

        // Creating the Objects of circle class
        Shape circle = new Circle(2);

        System.out.println("Area of circle: "
                           + circle.area());
    }
}

Output
Area of rectangle: 6.0
Area of circle: 12.56

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 particular data type but are not concerned about who implements its behavior.


Previous Article
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: publ
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
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
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 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 me
4 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 i
8 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 is
3 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 1 Java Code // Java program to demonstrate abstract class // cannot have instance public abstract cla
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
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 clas
10 min read
Article Tags :
Practice Tags :