Summary

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. They are used to specify a set of methods that a class must implement. Interfaces are a way to achieve abstraction and multiple inheritance in Java.

Example Code

// Define an interface
public interface Animal {
		int i = 34; // this is by default prefixed by public static final
    void eat(); // similarly it is by default prefixed by public abstract means it is defined as public abstract void eat();
    public abstract void sleep(); // same as void sleep
}

// Implement the interface in a class
public class Dog implements Animal {

    @Override
    public void eat() {
        System.out.println("Dog is eating");
    }

    @Override
    public void sleep() {
        System.out.println("Dog is sleeping");
    }

    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();
        dog.sleep();
    }
}

Note

  1. The function declared in Interfaces are always abstracted and provide 100% abstraction.
package interfaces;

public interface Shape {
    void calArea(int r); // same as public abstract void calArea();
}

class Circle implements Shape{
    public void calArea(int r){
        System.out.println("The area of the Circle: "+ Math.PI*r*r);
    }

    public static void main(String[] args) {
        Shape s = new Circle();
        s.calArea(5);
    }
}