Implementing Interfaces
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 35 of 87.
To use an interface, a class must implement it using the implements keyword. The class then provides concrete implementations for all methods declared in the interface:
public interface Drawable {
void draw();
}
public class Circle implements Drawable {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
}If a class implements an interface but doesn't provide implementations for all its methods, the compiler will throw an error. The @Override annotation is optional but recommended as it helps catch mistakes.
Just like with abstract classes, you can use an interface as a reference type. This enables polymorphism where different classes implementing the same interface can be treated uniformly:
Drawable shape1 = new Circle(5.0);
Drawable shape2 = new Rectangle(4.0, 3.0);
shape1.draw(); // Drawing a circle with radius 5.0
shape2.draw(); // Drawing a rectangle 4.0 x 3.0This is powerful because code that works with Drawable references doesn't need to know the specific class type. It only cares that the object can be drawn.
In the next lesson, you'll see how a single class can implement multiple interfaces simultaneously.
Challenge
EasyLet's build a speaker system that demonstrates how classes implement interfaces. You'll create an interface that defines what any speaker can do, then build two different speaker types that each implement this contract in their own way.
You'll organize your code across four files:
Speaker.java: Define an interface calledSpeakerthat declares what any speaker must be able to do. Every speaker should have aspeak()method that returns a String—this is the contract that all implementing classes must fulfill.Human.java: Create a class that implements theSpeakerinterface. A Human has anamefield (String). Include a constructor to initialize the name, and implement thespeak()method to return:[name] says: Hello everyone!Robot.java: Create another class that implements theSpeakerinterface. A Robot has amodelfield (String). Include a constructor to initialize the model, and implement thespeak()method to return:Robot [model] says: Beep boop!Main.java: Bring everything together using interface-based polymorphism. You'll receive two inputs: a human name and a robot model. Create a Human and a Robot, then store them in an array ofSpeakerreferences. Loop through the array and print the result of callingspeak()on each speaker.
You will receive two inputs: the human's name (String) and the robot's model (String).
Your output should show two lines—one for each speaker. Notice how both the Human and Robot can be treated uniformly through the Speaker interface, even though they speak in completely different ways!
Cheat sheet
A class uses the implements keyword to implement an interface and must provide concrete implementations for all methods declared in the interface:
public interface Drawable {
void draw();
}
public class Circle implements Drawable {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
}The @Override annotation is optional but recommended as it helps catch mistakes.
Interfaces can be used as reference types, enabling polymorphism where different classes implementing the same interface can be treated uniformly:
Drawable shape1 = new Circle(5.0);
Drawable shape2 = new Rectangle(4.0, 3.0);
shape1.draw(); // Drawing a circle with radius 5.0
shape2.draw(); // Drawing a rectangle 4.0 x 3.0Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
String humanName = scanner.nextLine();
String robotModel = scanner.nextLine();
// TODO: Create a Human object with the given name
// TODO: Create a Robot object with the given model
// TODO: Create an array of Speaker references containing both objects
// TODO: Loop through the array and print the result of speak() for each speaker
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System