Interface defines a contract: a set of abstract methods that a class must implement. Itβs used to achieve full abstraction and multiple inheritance in Java.
Example
interface Animal {
void makeSound(); // abstract by default
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark");
}
}
Animal animal = new Dog();
animal.makeSound(); // "Bark"
interface A { void show(); }
interface B { void display(); }
class Test implements A, B {
public void show() {}
public void display() {}
}
Features
- All methods are abstract + public by default (until Java 8+).
- Fields are
public static final
(constants). - A class can implement multiple interfaces.
- Can have:
- default methods (with body),
- static methods,
- private methods (since Java 9).
Comparison
Interface vs Abstract Class
Feature | Abstract Class | Interface |
---|---|---|
Method Types | Abstract + Concrete | Abstract (default), default, static |
Instantiation | β | β |
Constructors | β | β |
Multiple Inheritance | β | β |
Access Modifiers | Any | public only (before Java 8) |
Fields | Any | public static final only |
Tip
Use interfaces for flexibility and when multiple inheritance is needed.
Prefer abstract classes when you want to share a common code.
Parent: _OOP Advanced Tools