Object-Oriented Programming –
Interfaces
Understanding Interfaces in Java
What is an Interface?
• An interface is a contract that a class agrees to
follow.It contains method signatures without
implementations.The class that implements
the interface must provide implementation for
all its methods.
interface Animal {
void makeSound(); // abstract method
}
Key Features of Interfaces
• All methods are public and abstract by default.
• Interfaces support multiple inheritance.
• A class uses the implements keyword to
inherit from an interface.
• Variables in interfaces are public static final by
default.
Example
interface Animal {
void makeSound(); // Abstract method
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Bark
}
}
Why Use Interfaces?
• Achieve abstraction without using abstract
classes.
• Promote loose coupling.
• Support polymorphism.
• Allow multiple inheritance in Java.
Interface vs Abstract Class
Feature Interface Abstract Class
Purpose Defines a contract for what a class Provides partial abstraction and
can do, without saying how allows defining default behavior
Purpose interface, implements abstract, extends
Keywords Used interface, implements abstract, extends
Inheritance Supports multiple inheritance (a Single inheritance only
Support class can implement multiple
interfaces)
Use Case Used when unrelated classes need Used when classes share a
to implement the same behavior common base and some
(e.g., Flyable, Drivable) default functionality
Method Types Only abstract methods (Java 7)- Can have abstract and concrete
Default and static methods (Java 8+) (non-abstract) methods
Example Use Comparable, Runnable, Cloneable Shape, Employee, Animal (with
shared behavior)
Real-World Examples of Interfaces
Interface Real-world Analogy Example in Code
RemoteControl TV remote – all remotes TV, AC implement
have buttons, but RemoteControl
implementation may vary
Driveable Anything that can be Car, Bike implement
driven – cars, bikes, trucks Driveable
Real-World Examples of Interfaces
interface Driveable {
void drive();
}
class Car implements Driveable {
public void drive() {
System.out.println("Car is driving");
}
}
Polymorphism Using Interfaces
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() {
System.out.println("Drawing Circle");
}
} public class Main {
public static void main(String[] args) {
class Square implements Shape { Shape s1 = new Circle();
public void draw() { Shape s2 = new Square();
System.out.println("Drawing Square"); s1.draw(); // Drawing Circle
}
s2.draw(); // Drawing Square
}
}
}