Java Interface Example


Java coding comes with three types of classes – concrete classes, abstract classes and interfaces and comes with two keywords to inherit these classes – extends and implements. This tutorial is on how to use Java Interfaces with an example.

Basically, Java does not support multiple inheritance and infact it is a drawback, says every C++ Programmer. Infact, it is avoided to avoid the confusing concept of virtual functions. To overcome this, Designers introduced interfaces.

See the following code does not work as it is an example of Java multiple inheritance.

class Bird { }
class Animal { }
public class Ostrich extends Bird, Animal { }

Interface is not completely new. After all, it is a special type of abstract class where all methods should be abstract only. Just to inform the compiler that we are using interfaces, use implements keyword.

Example on Java interfaces and implements keyword
interface Animal                                // observe, interface keyword usage              
{
  public abstract void walk();                  // interface should have only abstract methods
}
interface Bird
{
  public abstract void fly();
}
public class Ostrich implements Bird, Animal   // observe, Java implements with interfaces
{
  public void walk()			       // overide abstract method of Animal
  {
    System.out.println("Animal walks");
  }
  public void fly()		               // overide abstract method of Bird
  {
    System.out.println("Birds fly");
  }
  public static void main(String args[])
  {
    Osrtrich o1 = new Ostrich();
    o1.walk();
    o1.fly();
  }
}


Java Interface
Output screenshot on using Java Interface

Observe, in the above code, Ostrich inherits two interfaces using implements keyword and not extends. After Java implements there should be interfaces only of any number.

To know more on inheritance with interfaces and implements refer Java Multiple Interfaces Inheritance.

Leave a Comment

Your email address will not be published.