Interfaces let you define a set of actions that different classes can do. Implementing interfaces helps make sure classes follow the same rules.
0
0
Implementing interfaces in Java
Introduction
When you want different classes to share the same actions but have different details.
When you want to make sure a class has certain methods before using it.
When you want to write code that works with many types of objects in the same way.
When you want to separate what a class can do from how it does it.
Syntax
Java
interface InterfaceName { returnType methodName(); } class ClassName implements InterfaceName { @Override public returnType methodName() { // method body } }
Use the implements keyword to say a class follows an interface.
All methods in an interface must be implemented in the class.
Examples
This example shows an interface
Animal with a method sound. The class Dog implements it and defines the sound.Java
interface Animal { void sound(); } class Dog implements Animal { @Override public void sound() { System.out.println("Woof"); } }
Here,
Vehicle interface has two methods. Car class implements both methods.Java
interface Vehicle { void start(); void stop(); } class Car implements Vehicle { @Override public void start() { System.out.println("Car started"); } @Override public void stop() { System.out.println("Car stopped"); } }
Sample Program
This program defines an interface Printer with a method print. Two classes implement it differently. The Main class creates objects and calls their print methods.
Java
interface Printer { void print(); } class InkjetPrinter implements Printer { @Override public void print() { System.out.println("Printing with Inkjet Printer"); } } class LaserPrinter implements Printer { @Override public void print() { System.out.println("Printing with Laser Printer"); } } public class Main { public static void main(String[] args) { Printer inkjet = new InkjetPrinter(); Printer laser = new LaserPrinter(); inkjet.print(); laser.print(); } }
OutputSuccess
Important Notes
Interfaces cannot have method bodies (except default or static methods in newer Java versions).
A class can implement multiple interfaces separated by commas.
Use @Override to help catch mistakes when implementing methods.
Summary
Interfaces define what methods a class must have.
Use implements keyword for a class to follow an interface.
All interface methods must be implemented in the class.