Introduce Java Interface and give examples
A Java interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors. The methods in interfaces are abstract by default, meaning they do not have a body and must be implemented by classes that choose to implement the interface.
Interfaces are used to achieve abstraction and multiple inheritance in Java. A class can implement multiple interfaces, allowing for a flexible design.
public
, static
, and final
.Here’s a simple example to illustrate the concept of interfaces in Java:
// Define an interface
interface Animal {
// Abstract method (no body)
void makeSound();
// Default method
default void eat() {
System.out.println("This animal eats food.");
}
}
// Implementing the interface in a class
class Dog implements Animal {
// Providing implementation for the abstract method
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
// Another class implementing the same interface
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
// Main class to test the interface and its implementations
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.makeSound(); // Output: Woof!
dog.eat(); // Output: This animal eats food.
Animal cat = new Cat();
cat.makeSound(); // Output: Meow!
cat.eat(); // Output: This animal eats food.
}
}
Animal
interface defines an abstract method makeSound()
and a default method eat()
.Dog
and Cat
classes implement the Animal
interface and provide their own implementations of the makeSound()
method.Dog
and Cat
can use the default eat()
method provided by the Animal
interface.In summary, interfaces are a powerful feature in Java that promote a clean and flexible design, allowing for abstraction and multiple inheritance.