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:
Declaration: Interfaces are declared using the
interface
keyword.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:
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
Post a Comment