What is the difference between an abstract class and an interface?
An abstract class is a partially built parent that can hold state, constructors and shared code, and a class can extend only one. An interface is a contract of methods that a class promises to provide, and a class can implement many.
Explain it simply
An abstract class is like a half-built house from a builder: walls and wiring are done (shared code and fields), and you finish the rooms your way. You can buy only one such house. An interface is like a certificate, such as "fire safe" or "wheelchair accessible". It lists rules you must meet, and one building can hold many certificates.
Example
abstract class Employee { // shared state + shared code
protected final String name;
Employee(String name) { this.name = name; }
String greet() { return "Hi, I am " + name; }
abstract double monthlyPay(); // children must decide
}
interface Payable { double amountDue(); } // contracts
interface Reportable { String report(); }
class Intern extends Employee implements Payable, Reportable {
Intern(String name) { super(name); }
double monthlyPay() { return 15000; }
public double amountDue() { return monthlyPay(); }
public String report() { return name + " earns " + monthlyPay(); }
}How it works
| Abstract class | Interface | |
|---|---|---|
| How many per class | One (single inheritance) | Many |
| Fields | Any fields, with state | Only constants (static final) |
| Constructors | Yes | No |
| Method bodies | Yes | Default and static methods (Java 8+) |
| Relationship | "is a" | "can do" |
Real-world use
- Abstract class: a base
Shape,EmployeeorRepositorywith shared logic and fields. - Interface: capabilities such as
Comparable,Runnable,Payable, or anything you want to mock in tests.
Common mistakes
- Using an abstract class when there is no shared state or code; an interface is lighter.
- Putting too many methods in one interface. Small, focused interfaces are easier to implement.
- Forgetting that interface methods are public, so implementing methods must be public too.
What to say in the interview
"An abstract class can have fields, constructors and implemented methods, and a class can extend only one, so I use it when related classes share state and behaviour, an 'is-a' relationship. An interface defines a contract a class promises to fulfil, and a class can implement many, so I use it for capabilities like Comparable or Payable. Since Java 8 interfaces can have default methods, but they still cannot hold instance state."
Follow-up questions
- Why does Java not allow multiple inheritance of classes?
- What problem do default methods solve?
- How do interfaces help with testing?