Actual use of interface in Java

 


We may come across with this interview question as "What is the actual use of interface in Java?". By this we may be thinking of, its an alternate for multiple interface which Java doesn't have and we can implement multiple interfaces in a Java class etc.,. Apart from these answers if we see in Object Oriented interface allows to use classes in different hierarchies by Polymorphism. Lets see simple example as how its works and interface used here



public interface Animal { 
 
 public int runningSpeed();
}

public class Horse implements Animal{

 @Override
 public int runningSpeed() {
  return 55;
 }
}

public class Zebra implements Animal{

 @Override
 public int runningSpeed() {
  return 40;
 }
}

public class AnimalsSpeed {
 
 public static void main(String[] args) {
  
  Animal a1 = new Horse();
  Animal a2 = new Zebra();
  
  System.out.println("Horse Speed "+a1.runningSpeed() + " mph");
  System.out.println("Zebra Speed "+a2.runningSpeed() + " mph");
  
 }
}

OUTPUT:

Horse Speed 55 mph
Zebra Speed 40 mph


If we see above example any number of classes, across class hierarchies could implement Animal interface in their own specific way. But still be used by some caller in a uniform way and by perspective of caller, it's just a Animal interface as we can see in AnimalsSpeed class. 

       Animal a1 = new Horse();
Animal a2 = new Zebra();

Welcome your comments for more use of interface in Java.




No comments:
Write comments