w1coding.comAll tutorials

Java Interfaces

Java lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Control
  5. Loops
  6. Arrays
  7. Methods
  8. OOP
  9. Contractors
  10. Inheritance
  11. Polymorphism
  12. Abtract
  13. Interfaces
  14. Constructors
  15. Static
  16. Exception
  17. Collections
  18. Lambda
  19. Streams
  20. Strings
  21. Date
  22. Interface
  23. Inheritance
  24. Polymorphism
  25. Exception
  26. File

Java Interfaces

Interfaces in Java allow you to define methods that must be implemented by any class that implements the interface. An interface cannot have method implementations, only method declarations.

Defining and Implementing Interfaces

interface Animal {
    void sound();
}

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

public class InterfaceExample {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.sound();
    }
}
    

This example defines an interface Animal with a method sound(). The Dog class implements the interface and provides its own implementation of sound().