Syntax error What does Interface consist of in Java

What does Interface consist of in Java



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
Updated on: 2019-07-30T22:30:24+05:30

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements