How to create and use interfaces in java?

Interfaces in Java allow for a form of multiple inheritance and can be used to achieve abstraction.

Example:


  interface Animal {
      void eat();
      void sleep();
  }

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

      public void sleep() {
          System.out.println("Dog sleeps");
      }
  }
  

Solution:

Using the implemented methods:


  Dog myDog = new Dog();
  myDog.eat();   // Outputs: Dog eats
  myDog.sleep(); // Outputs: Dog sleeps
  

Beginner's Guide to Java