Java Code Snippet

In Java, an interface operates as a reference type, akin to a class. It can encompass abstract methods, default methods, static methods, and constants. Direct instantiation of interfaces is impossible; they must either be implemented by classes or extended by other interfaces. The interface keyword is employed to define an interface. By default, methods in an interface are abstract, meaning they don't possess a defined body. Variables declared within an interface are intrinsically public, static, and final. The implements keyword is used when a class seeks to incorporate an interface. Notably, a single class can implement several interfaces, distinguishable by commas. Any class taking on an interface must furnish concrete realizations of all abstract methods from the interface unless the class itself bears the abstract designation. In this Java Interface Example, we declare an interface and a class that inherits from that interface. Click Execute to run the Java Interface Example online and see the result.
Java Code Snippet Execute
public class AnimalSounds {
    interface Animal {
        void sound();  // Abstract method for the sound
    }

    static class Dog implements Animal {
        @Override
        public void sound() {
            System.out.println("Woof!");
        }
    }

    public static void main(String[] args) {
        Animal dog = new Dog();

        dog.sound();  // Outputs: Woof!
    }
}
Updated: Viewed: 41 times