Explain the difference between an abstract class and an interface in Java, and when would you choose one over the other?

1 Answers
Answered by suresh

Abstract Class vs Interface in Java - Computer Science Category Interview Question

Abstract Class vs Interface in Java

Abstract Class:

An abstract class in Java is a class that cannot be instantiated on its own and can contain both abstract methods and concrete methods. It can have member variables and constructors. The keyword used to declare an abstract class is abstract.

Interface:

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. It cannot have member variables or constructors. The keyword used to declare an interface is interface.

Differences:

1. An abstract class can have abstract as well as non-abstract methods, while an interface can only have abstract methods.
2. A class can implement multiple interfaces but can extend only one abstract class.
3. An abstract class is a class, so it can have constructors, while an interface cannot have constructors.
4. Abstract classes are used to provide a partial implementation, while interfaces are used to specify contracts that classes must follow.

When to Choose Which:

Choose an abstract class when you want to provide a default implementation in your base class and have shared code among subclasses. Use an interface when you want to specify a set of methods that a class must implement, regardless of the actual implementation details.

Answer for Question: Explain the difference between an abstract class and an interface in Java, and when would you choose one over the other?