Interface in Java

 In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures (methods without a body), default methods, static methods, and nested types. It defines a contract for what a class can do, without specifying how it does it. Here's a breakdown:

  1. Declaration: Interfaces are declared using the interface keyword.

  2. Purpose: They allow you to specify a set of methods that a class must implement. This helps in achieving abstraction and multiple inheritance of type.

Example:

// Define an interface
interface Animal {
    // Method signatures (implicitly public and abstract)
    void makeSound();
    void eat();
}

// Implement the interface in a class
class Dog implements Animal {
    // Implementing the methods defined in the interface
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
    
    @Override
    public void eat() {
        System.out.println("Dog is eating...");
    }
}

// Using the interface
public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog(); // Instantiate Dog as Animal
        myDog.makeSound(); // Outputs: Woof!
        myDog.eat(); // Outputs: Dog is eating...
    }
}

Key Points:

  • Interfaces cannot be instantiated directly (you can't do new Animal()).
  • A class can implement multiple interfaces.

In Java, multiple inheritance (the ability of a class to inherit from more than one class) is not supported directly due to the potential for ambiguity and complexity. However, Java allows multiple inheritance of behavior (not state) through the use of interfaces.

A class can implement multiple interfaces, thus achieving multiple inheritance of behavior.

Example

Let's consider an example where we use interfaces to achieve multiple inheritance. We'll create two interfaces, Flyable and Swimmable, and a class Duck that implements both interfaces.

//Interface Flyable

interface Flyable {
    void fly();
}
 //Interface Swimmable 

 interface Swimmable {
    void swim();
}

//Class Duck Implementing Multiple Interfaces

class Duck implements Flyable, Swimmable {
    @Override
    public void fly() {
        System.out.println("The duck is flying.");
    }

    @Override
    public void swim() {
        System.out.println("The duck is swimming.");
    }
}
 

//Main class

public class Main {
    public static void main(String[] args) {
        Duck duck = new Duck();
        duck.fly();   // Outputs: The duck is flying.
        duck.swim();  // Outputs: The duck is swimming.
    }
}
 

Comments

Popular posts from this blog

KTU OOP LAB JAVA CSL 203 BTech CS S3 - Dr Binu V P

Syllabus and Practice Questions KTU OOPS Lab Java CSL 203

String Problems