← Exit to Module 6: Inheritance and Polymorphism lessons
Module progress · 0%Lesson · 30 min
Module 6: Inheritance and Polymorphism
Lesson focusInterfaces
Understand interfaces as a pure contract of behaviors. Learn how a class can implement multiple interfaces to achieve a form of multiple inheritance.
01 · 30 minInheritance Basics: The `extends` KeywordLocked02 · 30 minMethod Overriding, the `@Override` Annotation, and the `super` KeywordLocked03 · 30 minPolymorphism in ActionLocked04 · 25 minAbstract ClassesLocked05 · 30 minInterfacesLocked
What is an Interface? An interface is a completely abstract type that is used to group related methods with empty bodies. It is a contract that specifies what a class can do, without saying how it will do it.
Key Rules:
- An interface is declared using the
interfacekeyword.
- All methods in an interface are implicitly
publicandabstract(you don't need to type the keywords).
- A class uses the
implementskeyword to use an interface.
- A class can implement multiple interfaces. This is how Java achieves a form of multiple inheritance.
- A class that implements an interface must provide an implementation for all of its methods.
Interface vs. Abstract Class:
- Abstract Class: Can have both abstract and concrete methods. A class can only
extendone abstract class. Represents an 'is-a' relationship.
- Interface: Can only have abstract methods (with some exceptions in modern Java like
defaultmethods). A class canimplementmany interfaces. Represents a 'can-do' relationship (e.g., aCarand aBirdcan both implement theMovableinterface).
Default Methods (Java 8+): Modern interfaces can provide a default implementation for a method using the default keyword. This allows new methods to be added to interfaces without breaking existing classes that implement them.
interface Drawable {
void draw(); // public and abstract by default
}
interface Clickable {
void onClick();
}
// This class implements two interfaces
class Button implements Drawable, Clickable {
@Override
public void draw() {
System.out.println("Drawing a button.");
}
@Override
public void onClick() {
System.out.println("Button clicked!");
}
}