What is interfaces in Java?

In Java, an 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. Interfaces are a way to achieve abstraction and multiple inheritance in Java.

Once an interface is defined, a class can implement it by providing the body for the methods defined in the interface. A class that implements an interface must implement all the methods declared in the interface unless the class is abstract.

Interfaces are widely used in Java for various purposes such as polymorphism, achieving loose coupling, and enforcing a contract for the classes that implement them.

// Example of an interface in Java interface Animal { void sound(); // interface method (does not have a body) } class Dog implements Animal { public void sound() { System.out.println("Woof"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.sound(); // Outputs: Woof } }

Java Interfaces Programming Abstraction Multiple Inheritance Polymorphism