Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Difference between Abstract Class and Interface

Last Updated on May 18, 2023 by Prepbytes

In order to offer abstraction, both the Abstract class and the Interface are utilised. An interface is a design used to implement a class, whereas an abstract class declaration contains the abstract keyword. learning more about Java’s abstract class and interface differences. Let’s begin by defining what they mean.

What is Abstract Class in Java?

Java has a specific sort of class called an abstract class that is designed to be subclassed and cannot be created on its own. Multiple subclasses can share an abstract class’ common interface and partial implementation. They are capable of having both concrete (methods with a body) and abstract (methods without a body). All abstract methods in the superclass must have implementations, according to subclasses. Additionally, an abstract class may include constructors, static methods, and instance variables. An essential component of object-oriented programming that encourages code reuse and encapsulation is the usage of abstract classes.

Let us consider a simple example of the Shape class:

abstract class Shape {
    int x, y;

    // Constructor
    Shape(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // Abstract method
    abstract void draw();
}

class Circle extends Shape {
    int radius;

    Circle(int x, int y, int radius) {
        super(x, y);
        this.radius = radius;
    }

    // Override the abstract method
    void draw() {
        System.out.println("Drawing a Circle at (" + x + "," + y + ") with radius " + radius);
    }
}

class Rectangle extends Shape {
    int width, height;

    Rectangle(int x, int y, int width, int height) {
        super(x, y);
        this.width = width;
        this.height = height;
    }

    // Override the abstract method
    void draw() {
        System.out.println("Drawing a Rectangle at (" + x + "," + y + ") with width " + width + " and height " + height);
    }
}

class PrepBytes {
 
    // 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, 6, 6);
        rect.draw();
        System.out.println(" ");
 
        // Creating the Objects of circle class
        Shape circle = new Circle(12,12,5);
        circle.draw();
        System.out.println(" ");
    }
}

Output:

Drawing a Rectangle at (2,3) with width 6 and height 6

Drawing a Circle at (12,12) with radius 5

In the above example, the Shape class is an abstract class that defines a common interface and implementation for subclasses. The Circle and Rectangle classes extend the Shape class and provide their own implementation of the draw method.

Properties of Abstract Class in Java

Here are some of the properties of abstract classes in Java:

  • An abstract class can have both abstract and concrete methods.
  • An abstract class cannot be instantiated on its own and must be subclassed to be used.
  • Subclasses must provide implementations for all abstract methods in the superclass.
  • An abstract class can have instance variables, constructors, and static methods.
  • An abstract class can extend to another abstract class or concrete class.
  • An abstract class can implement one or more interfaces.
  • An abstract class can have inner classes, including abstract classes.
  • An abstract class can be used as a reference type to hold objects of its subclasses.

These properties make abstract classes a useful tool for promoting code reuse and encapsulation in object-oriented programming.

What is an Interface in Java?

An interface in Java is a blueprint for classes. It defines a set of methods and constants but does not provide any implementation. Classes that implement an interface must provide implementations for all the methods defined in the interface. Interfaces are used to define common functionality that can be shared among multiple classes.

Interfaces are a key aspect of object-oriented programming and provide several benefits, including:

  • Abstraction: Interfaces allow you to define a common interface for related classes, promoting abstraction and encapsulation.
  • Multiple inheritance: Java does not support multiple inheritance of classes, but a class can implement multiple interfaces, providing multiple inheritance of behavior.
  • Loose coupling: Interfaces promote loose coupling by allowing objects to interact with each other through a common interface without having to know the implementation details of each other.

Here is an example of how you could define an interface in Java:

import java.util.*;
class Phone {
    void makeCall(String person) {  
    }
    void sendMessage(String person) {   
    }
}
interface Camera {
    void clickPicture();
    void recordVideo();
}
class SmartPhone extends Phone implements Camera{
    public void clickPicture() {
        System.out.println("Auto focus on human face");
    }
    public void recordVideo() {
        System.out.println("Auto removal of background noise");
    }
    public void accessInternet() {
        System.out.println("Woah! I'm smart enough to do this");
    }
}
public class Main {
    public static void main(String[] args) {     
    }
}

So, in the above code, we have two classes, Phone and Camera, and one interface, SmartPhone. Real-world entities are represented by these classes. Now we must determine the connection between these three classes.
As we can see, the class SmartPhone in our code extends the class Phone and implements the Interface Camera. This is due to the fact that inheritance indicates an IS-A relationship, such as SmartPhone is a Phone. However, the interfaces indicate a HAS-A relationship, i.e. the SmartPhone has a Camera.

Properties of Interface in Java

Here are some of the properties of interfaces in Java:

  • Interfaces cannot be instantiated on their own and must be implemented by a class.
  • Interfaces can only contain abstract methods, constants, and default methods.
  • All methods in an interface are implicitly abstract and public, so they don’t need abstract and public keywords.
  • A class can implement multiple interfaces, allowing for multiple inheritance of behavior.
  • Interfaces cannot have instance variables, but they can have static variables.
  • One or more interfaces can be extended by an interface.
  • Interfaces are used to define common functionality that can be shared among multiple classes.
  • Interfaces are a form of abstraction, promoting loose coupling and allowing objects to interact with each other through a common interface.
  • These properties make interfaces a useful tool for defining common functionality and promoting abstraction and code reuse in object-oriented programming.

When to use Abstract Class in Java

Abstract classes are used in Java when you want to provide a common base class for a set of related classes. Here are some common use cases for abstract classes:

  • Code reuse: Abstract classes allow you to define common functionality that can be reused by multiple subclasses. This promotes code reuse and encapsulation, making your code more maintainable.
  • Implementation inheritance: Abstract classes allow you to provide a partial implementation that can be extended by subclasses. This can be useful when you want to enforce a certain level of consistency among related classes.
  • Abstract base class: An abstract class can act as an abstract base class, providing a common interface for a set of related classes. Subclasses of the abstract class must provide implementations for all abstract methods, ensuring that the set of related classes has a consistent interface.
  • Factory methods: Abstract classes can be used to provide factory methods, which are methods that create objects of the correct type for you. This can be useful when you have a number of related classes, and you want to provide a convenient way of creating objects for these classes.
  • Template method pattern: Abstract classes can be used to implement the template method pattern, where you define a common algorithm in the abstract class, and subclasses provide the specific steps of the algorithm. This allows you to define a common behavior that can be reused by multiple subclasses.

In general, you should use an abstract class when you want to define common functionality that can be shared by multiple subclasses, and when you want to enforce a certain level of consistency among related classes. However, if you only want to define a common interface and don’t need to provide any implementation, you should use an interface instead.

When to use Interface in Java

Interfaces are used in Java when you want to define a common interface for a set of related classes. Here are some common use cases for interfaces:

  • Define common behavior: Interfaces are used to define a common set of behaviors that can be shared by multiple classes. This allows objects to interact with each other through a common interface, promoting loose coupling and making your code more flexible and maintainable.
  • Multiple inheritance: Java does not support multiple inheritance of classes, but it does support multiple inheritance of interfaces. This allows a class to inherit behavior from multiple interfaces, providing a way to achieve multiple inheritance in Java.
  • Abstraction: Interfaces are a form of abstraction, promoting loose coupling and allowing objects to interact with each other through a common interface.
  • Code reuse: Interfaces allow you to define common functionality that can be reused by multiple classes, promoting code reuse and making your code more maintainable.
  • Enforce consistency: Interfaces can be used to enforce a certain level of consistency among related classes. By requiring that classes implement a common interface, you can ensure that they have a consistent set of behaviors, making it easier to work with them and making your code more maintainable.

In general, you should use an interface when you want to define a common interface for a set of related classes, and when you want to enforce a certain level of consistency among related classes. If you need to provide a partial implementation that can be extended by subclasses, you should use an abstract class instead.

Difference between Abstract Class and Interface

Abstract classes and interfaces are two different concepts in Java that provide ways to define common behavior and promote code reuse. Here are some key difference between abstract class and interface:

            Abstract Class                      Interface
Both abstract and concrete methods can be found in an abstract class. Interface, on the other hand, only contains abstract methods
An abstract class can extend another abstract class or a concrete class. One or more interfaces can be extended by an interface.
An abstract class can have a constructor. An interface cannot have a constructor.
An abstract class can have all four; static, non-static, and final, non-final variables. Only final and static variables are used
It has class members like private and protected, etc. It has class members public by default.
To declare abstract class abstract keywords are used. The interface can be declared with the interface keyword.
The keyword ‘extend’ is used to extend an abstract class The keyword implement is used to implement the interface.

Conclusion
Both interfaces and abstract classes outline a list of conditions that must be met by the implementing class. An abstract method that anticipates being defined in the implementing class can be specified in either scenario. Otherwise, a compilation error will cause the code to fail.

Classes can mimic numerous inheritances via an interface. Interfaces provide notions with a high-level explanation before they are implemented and expressed explicitly. Therefore, an interface comes in handy for integrating different API contracts without the requirement for implementing classes to be connected.

An abstract class is preferable when the implementing classes must be linked. You can define non-static, non-final, final, and static methods and attributes as well as private and protected methods and attributes in an abstract class. Additionally, there is only one abstract class from which the implementing class can derive.

FAQs related to the Difference between Abstract Class and Interface

Below are some frequently asked questions on abstract class and interface in java

Question 1 – In which situation is interface better than abstract class?
Ans – Interfaces are better than abstract classes in situations where you need to achieve multiple inheritance, loose coupling, improved testability, increased flexibility, and better organization. However, it is important to note that both abstract classes and interfaces have their own strengths and weaknesses, and the choice between them depends on the specific requirements of your project.

Question 2 – Why abstract class is faster than interface in Java?
Ans – Abstract classes and interfaces have different design goals in Java and it is not accurate to say that one is faster than the other.
The performance difference between abstract classes and interfaces is not significant in most cases, and the choice between them should be based on their design goals rather than performance considerations. Interfaces are used when you need to define a contract that specifies the behavior of a class, and abstract classes are used when you want to provide a common implementation for some of the methods in a class hierarchy.

Question 3 – What are the limitations of interfaces compared to abstract classes?
Ans – Interfaces have the following limitations compared to abstract classes in Java:

  • No instance variables: Interfaces cannot have instance variables. If a class needs to have instance variables, it must use an abstract class instead of an interface.
  • No constructor: Interfaces cannot have a constructor, so you cannot provide any initialization for the classes that implement an interface.
  • No access to default methods: Interfaces can only declare public methods, which means that you cannot use default methods to provide a default implementation for the methods in an interface.
  • No access to protected methods: Interfaces cannot access protected methods, so if a class needs to access protected methods, it must use an abstract class instead of an interface.

Question 4 – What is the similarity between interface and abstract class?
Ans – Abstract classes and interfaces have the following similarities in Java:

  • Abstract methods: Both abstract classes and interfaces can declare abstract methods, which are methods without a body. The classes that extend an abstract class or implement an interface must provide an implementation for the abstract methods.
  • Encapsulation: Both abstract classes and interfaces provide a way to encapsulate behavior and data, making it easier to maintain and reuse code.
  • Abstraction: Both abstract classes and interfaces are used to define abstract data types, providing a level of abstraction between the implementation and the interface.
  • Reusability: Both abstract classes and interfaces can be used as a blueprint for creating concrete classes, making it easier to reuse code and implement common behavior.

Leave a Reply

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