The Wayback Machine - https://web.archive.org/web/20240910184812/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 : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
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.



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
Java | Abstract Class and Interface | Question 1
Which of the following is FALSE about abstract classes in Java (A) If we derive an abstract class and do not implement all the abstract methods, then the derived class should also be marked as abstract using 'abstract' keyword (B) Abstract classes can have constructors (C) A class can be made abstract without any abstract method (D) A class can inh
1 min read
Java | Abstract Class and Interface | Question 2
Which of the following is true about interfaces in java. 1) An interface can contain following type of members. ....public, static, final fields (i.e., constants) ....default and static methods with bodies 2) An instance of interface can be created. 3) A class can implement multiple interfaces. 4) Many classes can implement the same interface. (A)
1 min read
Java | Abstract Class and Interface | Question 3
Predict the output of the following program. abstract class demo { public int a; demo() { a = 10; } abstract public void set(); abstract final public void get(); } class Test extends demo { public void set(int a) { this.a = a; } final public void get() { System.out.println("a = " + a); } public static void main(String[] args) { Test obj =
1 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
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 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
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
Differences between Interface and Class in Java
This article highlights the differences between a class and an interface in Java. They seem syntactically similar, both containing methods and variables, but they are different in many aspects. Differences between a Class and an Interface The following table lists all the major differences between an interface and a class in Java language: Class In
4 min read
Difference between Inheritance and Interface in Java
Java is one of the most popular and widely used programming languages. Java has been one of the most popular programming languages for many years. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In this article, we will understand the difference
3 min read
Difference Between poll() and remove() method of Queue Interface in Java
The queue is a data structure that stores elements in a first-in, first-out (FIFO) order. It can be used to implement a priority queue or as a basic synchronization primitive. The remove() method removes an element from the head of this queue and returns it. The poll() method blocks until one or more elements become available for removal, then retu
4 min read
Difference Between Package and Interface in Java
In Java, packages and interfaces play crucial roles in organizing and structuring code. They serve different purposes and are used in distinct contexts. In this article, we will learn the concepts of the packages and interfaces in Java. syntax provides examples for each and then presents a table highlighting the key differences between them. Differ
2 min read
Why can't static methods be abstract in Java?
In Java, a static method cannot be abstract. Doing so will cause compilation errors.Example: Java Code // Java program to demonstrate // abstract static method import java.io.*; // super-class A abstract class A { // abstract static method func // it has no body abstract static void func(); } // subclass class B class B extends A { // class B must
3 min read
Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?
Prerequisite: Interface and Abstract class in Java. A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created. Why interfaces can not have the constructor? An Interface is a complete abstraction of class. All data members present in the interface are by de
4 min read
Why a Constructor can not be final, static or abstract in Java?
Prerequisite: Inheritance in Java Constructor in java is a special type of method which is different from normal java methods/ordinary methods. Constructors are used to initialize an object. Automatically a constructor is called when an object of a class is created. It is syntactically similar to a method but it has the same name as its class and a
6 min read
Abstract Syntax Tree (AST) in Java
Abstract Syntax Tree is a kind of tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code. There is numerous importance of AST with application in compilers as abstract syntax trees are data structures widely used in compilers to
5 min read
Abstract vs Public Access Modifier in Java
Access Modifier in Java is the reserved keyword used to define the scope of a class, variable, and methods. It also tells us about that whether child class creation is possible or not or whether object creation is possible or not. Abstract Access Modifier is a modifier applicable only for classes and methods but not for variables. If we declare any
4 min read
Java Error - All illegal Modifier Combinations For Methods w.r.t Abstract
In Java, we can apply a variety of modifiers to classes, methods, blocks, and variables and each one has a different use case and all of these primarily define how and where those classes, methods, blocks, and variables can be accessed and modified. But not all the modifiers can be applied simultaneously due to some contradiction among their defini
6 min read
abstract keyword in java
In Java, abstract is a non-access modifier in java applicable for classes, and methods but not variables. It is used to achieve abstraction which is one of the pillars of Object Oriented Programming(OOP). Following are different contexts where abstract can be used in Java. Characteristics of Java Abstract KeywordIn Java, the abstract keyword is use
7 min read
Abstract Method in Java with Examples
In Java, Sometimes we require just method declaration in super-classes. This can be achieved by specifying the Java abstract type modifier. Abstraction can be achieved using abstract class and abstract methods. In this article, we will learn about Java Abstract Method. Java Abstract MethodThe abstract Method is used for creating blueprints for clas
6 min read
Controlling the Visibility of Class and Interface in Java
Maintenance is one of the important aspects of software development, and experience has shown that software that maintains its component's visibility low is more maintainable than one that exposes its component more. You're not going to know it upfront, but when redesigning the application, you're going to miss it terribly. You end up patching and
5 min read
Messages, aggregation and abstract classes in OOPS
Object-Oriented Programming System (OOPS) is the basic concept of many programming languages. It is a paradigm based on the object which contains methods and data. This concept is used to make programming a class and object model which behaves like a real-world scenario. In this article, we'll learn about messages, aggregation, composition and abst
5 min read
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all functions cannot be provided in a base class because we don't know the implementation. Such a class is called an abstract class.For example, let Shape be a base class. We cannot provide the implementation of function draw() in Shape, but we know every derived class must have an implementation of draw(). Similarly, an
6 min read
Java 8 | DoubleToIntFunction Interface in Java with Example
The DoubleToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an int-valued result. The lambda expression assigned to an object of DoubleToIntFunction type is used to define
1 min read
Java 8 | IntToDoubleFunction Interface in Java with Examples
The IntToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a double-valued result. The lambda expression assigned to an object of IntToDoubleFunction type is used to define
1 min read