Interfaces in Java


An interface in Java is a reference type that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields. The methods in interfaces are abstract by default.

Source Code

interface Animal {
    void eat(); // Interface method (does not have a body)
}

class Cat implements Animal {
    public void eat() {
        System.out.println("The cat eats.");
    }
}

public class TestInterface {
    public static void main(String[] args) {
        Cat myCat = new Cat();
        myCat.eat();
    }
}

Interfaces specify what a class must do and not how. It’s a way to achieve abstraction and multiple inheritance in Java.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments