Interface
An interface is a completely abstract type in Java that defines a set of methods a class must implement, without providing (in most cases) any implementation itself. It represents a "contract" that implementing classes must follow.
1. What is an Interface?
An interface is a completely abstract type in Java that defines a set of methods a class must implement, without providing (in most cases) any implementation itself. It represents a "contract" that implementing classes must follow.
2. Why is it used?
Interfaces let unrelated classes share a common set of expected behaviours, and they allow Java to support something close to multiple inheritance, since a class can implement multiple interfaces at once.
3. Real-Life Example
Think of a job advertisement listing required skills, like "must know driving and cooking." Anyone who takes the job (implements the interface) must actually have those skills — the advertisement itself doesn't do the driving or cooking.
4. Syntax
javainterface InterfaceName { void methodName(); // implicitly public and abstract } class ClassName implements InterfaceName { public void methodName() { // implementation } }
5. Example Program
javainterface Drivable { void drive(); } class Car implements Drivable { public void drive() { System.out.println("Car is being driven"); } } public class InterfaceDemo { public static void main(String[] args) { Drivable d = new Car(); d.drive(); } }
Output:
Car is being driven6. Key Points to Remember
- A class uses
implementsto use an interface, and must provide implementations for all its methods. - A class can implement multiple interfaces at once, unlike extending multiple classes.
- Since Java 8, interfaces can also have
defaultandstaticmethods with actual implementations.