Advanced Java Programming - Old Questions

1. What is interface? How can you use the concept of interface to achieve multiple inheritance? Discuss with suitable example.

10 marks | Asked in 2070

An interface in Java is a blueprint of a class. It has static constants and abstract methods. An interface is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in java.

In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through InterfacesAn interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.

Multiple inheritance can be achieved with interfaces, because the class can implement multiple interfaces. To implement multiple interfaces, separate them with a comma.

In the following example Class Animal is derived from interface AnimalEat and AnimalTravel.

interface AnimalEat {
   void eat();
}
interface AnimalTravel {
   void travel();
}
class Animal implements AnimalEat, AnimalTravel {
   public void eat() {
      System.out.println("Animal is eating");
   }
   public void travel() {
      System.out.println("Animal is travelling");
   }
}