What does Interface consist of in Java

Java 8Object Oriented ProgrammingProgramming

An interface can be defined using the interface keyword. It contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. An interface is primarily used to implement abstraction and it cannot be instantiated.

A program that demonstrates an interface in Java is given as follows:

Example

 Live Demo

interface AnimalSound {
   abstract void sound();
}
class CatSound implements AnimalSound {
   public void sound() {
      System.out.println("Cat Sound: Meow");
   }
}
class DogSound implements AnimalSound {
   public void sound() {
      System.out.println("Dog Sound: Bark");
   }
}
class CowSound implements AnimalSound {
   public void sound() {
      System.out.println("Cow Sound: Moo");
   }
}

public class Demo {
   public static void main(String[] args) {
      AnimalSound a = new CatSound();
      a.sound();
   }
}

Output

Cat Sound: Meow
raja
Published on 15-Feb-2019 14:50:10
Advertisements