An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. It is used to specify a set of methods that a class must implement.
interface Animal {
void sound(); // Abstract method
}
class Dog implements Animal {
public void sound() {
System.out.println("Woof");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
}
}
The Dog class implements the Animal interface and provides the implementation for the sound() method.
interface Animal {
void sound();
}
interface Playable {
void play();
}
class Dog implements Animal, Playable {
public void sound() {
System.out.println("Woof");
}
public void play() {
System.out.println("Playing fetch");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
dog.play();
}
}
Java allows a class to implement multiple interfaces. In this example, the Dog class implements both Animal and Playable interfaces.