What is the difference between abstract class and interface in Java, and when would you use each one?

1 Answers
Answered by suresh

Difference between Abstract Class and Interface in Java for Java Programmer Interview Question

Difference between Abstract Class and Interface in Java

An abstract class is a class in Java that cannot be instantiated on its own and can contain both abstract and concrete methods. An abstract class can have instance variables whereas an interface is a reference type in Java that is similar to class but contains only static constants and abstract methods.

When to use Abstract Class:

  1. When there is a need for defining a common base class that should be extended by all the derived classes.
  2. When you want to provide a default implementation of certain methods that can be overridden by the derived classes.
  3. When there is a need to define constructor in the class and reuse the code in the derived classes.

When to use Interface:

  1. When there is no need for the default implementation of methods.
  2. When you want to achieve multiple inheritance by implementing multiple interfaces.
  3. When the contract between the class and the outside world needs to be defined.
Answer for Question: What is the difference between abstract class and interface in Java, and when would you use each one?