Abstract Class vs Interface – Wipe Out all your Doubts!

In Java, the Abstract classes and interfaces are fundamental building blocks as they both are used to implement one of the essential concepts of Object-Oriented Programming that is, Abstraction.

Though both of them are used for Abstraction, they differ from each other, and we cannot use them interchangeably. We will compare abstract class vs interface, along with real-life examples. We will also discuss when we should use interfaces and abstract classes.

In our last tutorial, we studied about abstract class in Java and also discussed the interfaces in Java in our previous articles. In this article, we are going to discuss the differences between Abstract Class vs Interface in Java.

difference between Abstract Class vs Interface in Java

Abstract Class In Java

An Abstract class is a class whose objects can’t be created. It is a kind of guideline or a template for other classes. An abstract class should contain at least one abstract method (method without any implementation or method body).

  • The abstract class is declared with the help of an abstract keyword.
  • An abstract class can be considered as an incomplete class that does not represent complete behavior.
  • The abstract class can have abstract methods (methods without body) as well as concrete methods (methods with the body).
  • We can not create objects or instances from the abstract classes, but they can be subclassed.

Syntax of writing Abstract classes:

abstract class TestAbstractClass
{
  public abstract void abstractMethod();
  public void normalMethod()
  {
    //method body
  }
}

Reasons For Using Abstract Class in Java

  • An abstract class provides a guideline or template for other future specific classes.
  • An Abstract class gives a default functionality of Inheritance.
  • The abstract class helps in achieving code reusability.
  • The abstract class also allows us to define a common interface for its subclasses.

Get to know more about Java Inheritance in detail with Techvidvan.

Follow TechVidvan on Google & Stay updated with latest technology trends

Abstract Methods in Java

  • Abstract methods are methods with no implementation. They do not contain any method statement.
  • The child classes of this abstract class must provide the implementation of these inherited abstract methods.
  • An abstract method is declared with an abstract keyword.
  • The declaration of an abstract method must end with a semicolon ;

Check out the different Java Methods you didn’t know about.

Syntax of declaring abstract methods:

access-specifier abstract return-type method-name();

Example of Abstract class:

package com.techvidvan.abstractclass;
//parent class
abstract class Animal
{
  //concrete method
  public void show1()
  {
    System.out.println("Concrete method of parent class Class");
  }
  //abstract method
  abstract public void show2();
  }
//child class
Class Dog extends Animal
{
  // Must Override this method while extending the parent class
  public void show2()
  {
    System.out.println("Overriding abstract method of parent class");
  }

  //Overriding concrete method is not compulsory
  public void show1()
  {
    System.out.println("Overriding concrete method of parent class");
  }
}
public class AbstractClassDemo
{
  public static void main(String[] args)
  {
    Dog obj = new Animal();
    obj.show2();
    obj.show1();
  }
}

Output:

Overriding abstract method of parent class
Overriding concrete method of parent class

Rules to be followed for Abstract Class

  • The abstract class cannot be instantiated or we can’t create objects from abstract classes.
  • The child class which extends the abstract class should implement all the abstract methods of the parent class otherwise, the child class should also be declared as an abstract class.

Interfaces in Java

An interface is another building block of Java which is a blueprint or template of a class. It is much similar to the Java class but the only difference is that it has abstract methods and static constants.

There can be only abstract methods in an interface, that is there is no method body inside these abstract methods. The class that implements the interface should be declared as abstract, otherwise, all the methods of the interface need to be defined in the class.

Explore our article on Interface in Java to learn in detail.

Syntax of declaring Interfaces in Java:

To declare an interface, the interface keyword is used. Here is a syntax to declare an interface:

interface interface-name
{
  //abstract methods
}

Example:

Following is an example of an interface:

//Filename: NameOfInterface.java

                    import java.lang.*;
                    // Any number of import statements

                    interface NameOfInterface
                    {
                           // Any number of final, static fields
                           // Any number of abstract method declarations
                    }

Example:

//Filename : Animal.java

interface Animal
{
   public void eat();
   public void travel();
}

Reasons For Using Interfaces in Java

  • It allows us to achieve a complete abstraction.
  • Interfaces are mainly designed to support dynamic method resolution at run time.
  • Interfaces allow us to achieve loose coupling.
  • It also helps us to separate the definition of a method from the inheritance hierarchy.

Implementing Interfaces

A class implementing an interface can be thought of as the class assigning a contract. This means that the class agrees to perform the specific behaviors of the Interface. Unless a class is declared as abstract, it should perform all the behaviors of the Interface.

In order to implement an Interface in Java, a class uses the implements keyword. The implements keyword appears in the class declaration after the extends portion of the declaration.

Code to understand Interfaces in Java:

package com.techvidvan.interfaces;
interface Polygon
{
  //declaring variables of the interface
  public static final int length = 4,breadth = 8;
  //declaring interface methods(without a method body)
  public void getName();
  public void getNumberOfSides();
  public void getArea();
  public void getPerimeter();
}

// Rectangle class "implements" the Polygon interface
class Rectangle implements Polygon
{
  public void getName()
  {
    // The body of getName() is provided here
    System.out.println("The name of the Polygon is: Rectangle");
  }
  public void getNumberOfSides()
  {
    // The body of getNumberOfSides() is provided here
    System.out.println("There are 4 sides in a Rectangle");
  }
  public void getArea()
  {
    // The body of getArea() is provided here
    System.out.println("The Area of Rectangle is: " +length*breadth);
  }
  public void getPerimeter()
  {
    // The body of getPerimeter() is provided here
    System.out.println("The Perimeter of Rectangle is: " +2*(length + breadth));
  }
}

class InterfaceDemo
{
  public static void main(String[] args)
  {
    Rectangle rectangle = new Rectangle(); // Create a Rectangle object

    //calling methods of class Rectangle
    rectangle.getName();
    rectangle.getNumberOfSides();
    rectangle.getArea();
    rectangle.getPerimeter();
  }
}

Output:

The name of the Polygon is: Rectangle
There are 4 sides in a Rectangle
The Area of Rectangle is: 32
The Perimeter of Rectangle is: 24

Rules to be followed for Interface

  • The class that implements the Interface should implement all the methods defined in the Interface.
  • An Interface can also contain final variables.

Abstract Class vs Interface in Java

We will compare Abstract Class vs Interface on the basis of following parameters:

S.NoParameterAbstract ClassInterfaces
1.Keyword UsedAn abstract keyword is used to create an abstract class.An interface keyword is used to create an interface.
2.Type of variablesAbstract class in Java can have both final, non-final, static and non-static variables.An interface can only have final and static variables that are declared by default.
3.final variablesAn abstract class may or may not have variables declared as final In interfaces, variables are by default declared as final.
4.Access ModifiersAbstract classes can have all access modifiers: public, protected, private and default.No other access modifiers are allowed except the public access modifier.
5.Type of MethodsAn abstract class can have both abstract and non-abstract or concrete methods.An interface can only have abstract methods. From version 8 of Java, the interface supports static and non-static methods too.
6.ConstructorsAn abstract class can have constructorsAn interface can not have constructors
7.Multiple InheritanceAbstract classes do not support Multiple Inheritance. A class can extend only a single abstract class but can implement multiple Java interfaces.Interfaces support Multiple Inheritance.
8.ImplementationWe can extend an abstract class using the extends keyword.We can implement an interface using the implements keyword.
9.SpeedFastSlow as it requires extra indirection.
10.When to useTo avoid independenceFor Future enhancement

When to use Abstract Class?

Consider using abstract classes in the following cases:

  • If you have some related classes that need to share the same lines of code, then we put these classes in abstract classes.
  • If there is a requirement of using access modifiers other than public such as protected and private for methods or fields.
  • When there is a need for defining a state of an object because we need to define a non-static or non-final field.

When to use Interface?

Consider using an interface in the following cases:

  • When you want to achieve 100% abstraction.
  • If you want to achieve multiple inheritance, that is, implementing more than one interface.
  • When you want to specify the behavior of a particular data type irrespective of who implements its behavior.

Summary

Abstract class and interfaces are very important aspects of OOPs in Java. They help us to achieve Abstraction in Java. In this article of Java, we learned the difference between Abstract class vs Interface on the basis of various parameters, with their syntax and implementation.

We also discussed when and where to use the abstract classes and Interface in Java. This article will surely guide you to the right path in Java.

Thank you for reading our article. If you have any queries related to Abstract Class vs Interface in Java, do let us know by dropping a comment below.

Happy Learning 🙂

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


1 Response

  1. John says:

    Unless you’re using an incredibly old JVM you’re unlikely to see a tangible performance benefit to using abstract classes over interfaces, defining them as “fast” vs “slow” is a stretch. As of java 8 there’s actually very few reasons for using abstract classes. The only reason you specifically need an abstract class is when you’re modelling something stateful, the internal state of what you’re modelling can be modelled in the same way for all concrete implementations and you’re going to benefit from code reuse surrounding the areas of code that manipulate the internal state. Otherwise use an interface.

Leave a Reply

Your email address will not be published. Required fields are marked *