Easy java core-java

What is the difference between an interface and an abstract class?

The 30 second answer

An abstract class can have state, constructors and any access level, and a class can extend only one. An interface defines a contract: it has no instance fields, but since Java 8 it can have default and static methods, and a class can implement many interfaces. I use an interface for a capability many unrelated classes share, like Comparable or PaymentMethod, and an abstract class when closely related classes share code and fields.

<!-- level: 1 --> <!-- must_know: true -->

Abstract classInterface
InheritanceA class extends oneA class implements many
FieldsInstance fields, any modifierOnly public static final constants
ConstructorsYesNo
MethodsAbstract and concrete, any accessAbstract, default, static, private (Java 9+)
Typical useShared code among related classesA contract or capability for unrelated classes

The Java tutorial gives the guideline. Consider an abstract class when you want to share code among closely related classes, expect subclasses to need common fields or non-public methods, or need non-static, non-final fields. Consider an interface when unrelated classes will implement it (like Comparable or Cloneable), when you want to describe a behaviour without caring who implements it, or when you need multiple inheritance of type.

Default methods are covered in more depth in What is the difference between default and static methods in interfaces?.

Sources (2)
  1. Java tutorial: Abstract methods and classesdocs.oracle.com
  2. dev.java: Abstract methods and classesdev.java