Java Interfaces
Interfaces in Java allow you to define methods that must be implemented by any class that implements the interface. An interface cannot have method implementations, only method declarations.
Defining and Implementing Interfaces
interface Animal {
void sound();
}
class Dog implements Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
}
}
This example defines an interface Animal with a method sound(). The Dog class implements the interface and provides its own implementation of sound().