المشاركات

OOP Pillar: Interfaces (implements keyword)

Learn Java OOP Interfaces with the implements keyword. Understand abstraction, multiple interfaces, and how classes provide their own implementations.
OOP Pillar: Interfaces (implements keyword)

On Day 26, we focus on Interfaces, another core pillar of OOP in Java. An interface is like a contract that defines methods (without implementation). A class that implements an interface must provide the implementation for all its methods. Interfaces help achieve 100% abstraction and allow multiple inheritance in Java.

1. Defining and Implementing an Interface


interface Animal {
    void sound(); // abstract method by default
    void eat();
}

class Dog implements Animal {
    @Override
    public void sound() {
        System.out.println("Dog barks");
    }

    @Override
    public void eat() {
        System.out.println("Dog eats bones");
    }
}

class Cat implements Animal {
    @Override
    public void sound() {
        System.out.println("Cat meows");
    }

    @Override
    public void eat() {
        System.out.println("Cat drinks milk");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a1 = new Dog();
        Animal a2 = new Cat();

        a1.sound();
        a1.eat();

        a2.sound();
        a2.eat();
    }
}

Explanation: The Dog and Cat classes implement the Animal interface by providing their own definitions of sound() and eat().

2. Multiple Interfaces


interface Printable {
    void print();
}

interface Scannable {
    void scan();
}

class Printer implements Printable, Scannable {
    @Override
    public void print() {
        System.out.println("Printing document...");
    }

    @Override
    public void scan() {
        System.out.println("Scanning document...");
    }
}

public class Main {
    public static void main(String[] args) {
        Printer p = new Printer();
        p.print();
        p.scan();
    }
}

Explanation: Unlike classes, Java allows implementing multiple interfaces. This is how Java overcomes the lack of multiple class inheritance.

3. Why Use Interfaces?

  • Provide complete abstraction.
  • Allow multiple inheritance in Java.
  • Standardize method signatures across different classes.
  • Make code more flexible and scalable.

Summary

Interfaces define a contract for classes to follow. Using the implements keyword, a class provides specific implementations. Interfaces allow polymorphism, code reusability, and multiple inheritance.

إرسال تعليق