Interview Q&A · Java · 4 questions in this topic
Abstract Classes vs Interfaces, Constructors, Abstract Methods — Java Interview Q&A
When to choose an abstract class, what abstract members guarantee, and how modern interfaces differ. Part of OOP Mechanics · 294 questions in the Java bank.
What is the difference between an abstract class and an interface?
Answer
An abstract class can hold instance state, constructors, and members with any access level, while an interface mainly defines a contract and since Java 8 can also provide default and static methods, plus private helpers since Java 9. Fields in an interface are always public static final constants, whereas an abstract class can declare mutable instance fields. A class can extend only one abstract or concrete class but can implement many interfaces, which is how Java supports multiple inheritance of behavior. Use an abstract class to share state and common code in one hierarchy, and use an interface to define capabilities that unrelated classes can adopt. Since Java 17, both can be sealed to restrict which types may extend or implement them.
Key points
- 1Abstract classes allow state, constructors, and any access level, while interfaces favor behavior contracts.
- 2Interface methods are public by default and may be abstract, default, static, or private.
- 3Prefer interfaces for capabilities across hierarchies and abstract classes for shared skeletal implementation.
What are abstract classes?
Answer
An abstract class is declared with the abstract keyword when one or more behaviors cannot usefully be implemented yet and must be left to subclasses. It cannot be instantiated, but it may mix abstract methods with fully implemented methods and fields. A subclass must implement all inherited abstract methods or itself be declared abstract, while callers can use an abstract type as a reference that points to concrete subclass objects.
Can an abstract class have a constructor?
Answer
Yes, an abstract class can declare constructors and the code compiles and runs normally. The constructor executes through the normal super chain when a concrete subclass is created, so it initializes inherited fields and enforces required setup. The old claim that such a constructor is useless is wrong because without it each subclass would duplicate the initialization logic.
Example
abstract class Vehicle { Vehicle(String name) {} } class Car extends Vehicle { Car() { super("car"); } }
What are abstract methods?
Answer
An abstract method declares only a signature with the abstract keyword and ends with a semicolon instead of a body. It states required behavior without choosing an implementation. Each concrete subclass must provide an implementation, which is how abstract classes enforce a common protocol while allowing varied behavior.
Example
abstract class Shape { public abstract double area(); }
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission