Interfaces Multiple Inheritance Java

April 6, 2011 | oops-concepts

We know earlier, Java does not support multiple inheritance, basically. But to support multiple inheritance, partially, Java introduced "interfaces". An interface is not altogether a new one for us; just it is a special flavor of abstract class where all methods are abstract. That is, an interface contains only abstract methods.

Syntax of multiple inheritance with two interface
interface Suzuki
{
  public abstract void body();
}
interface Ford
{
  public abstract void engine();
}
public class MotorCar implements Suzuki, Ford
{
  public void body()
  {
    System.out.println("Fit Suzuki body");
  }
  public void engine()
  {
    System.out.println("Fit Ford engine");
  }
  public static void main(String args[])
  {
    MotorCar mc1 = new MotorCar();
    mc1.body();
    mc1.engine();
  }
}

[caption id="attachment_284" align="aligncenter" width="414" caption="Output screen of MotorCar.java"]Interfaces Multiple Inheritance[/caption]

In the above code there are two interfaces - Suzuki and Ford. Both are implemented by MotorCar because it would like to have the features of both interfaces. For this reason (to have the functionality of many classes) only, Java supports multiple inheritance through interfaces. Just to inform there are multiple interfaces and not classes, tell the compiler by replacing "extends" with "implements". MotorCar, after implementing both the interfaces, overrides the abstract methods of the both - body() and engine(); else program does not compile. Java supports multiple inheritance partially through interfaces. Following figure gives the view of the above interfaces.

Interfaces Multiple Inheritance

Features of Interfaces

Interfaces are derived from abstract classes with a special additional rule that interfaces should contain only abstract methods. Let us see some more properties.

  1. Interfaces support multiple inheritance which is not possible with concrete and abstract classes.
  2. "implements" keyword is used in place of "extends". "extends" comes with concrete and abstract classes.
  3. Interfaces must contain abstract methods only.
  4. As in abstract classes, all the abstract methods of the interfaces should be overridden by the subclass.
  5. As with abstract classes, with interfaces also, objects cannot be created but reference variables can be created.
  6. Interface reference variable can be assigned with concrete subclass objects. Once assigned, the interface reference variable works like an object. This feature applies to abstract classes also.
  7. As all methods must be abstract and public, these two keyword can be omitted in method declaration. If omitted, JVM takes by default.
  8. All interface variables must be public, static and final. If omitted, they are taken by default.
  9. All interface methods should be overridden with public only as overridden method cannot have a weaker access specifier.

Later you get a table where actual differences between abstract classes and interfaces are given.

Defining an Interface

We know earlier, interface should have only abstract methods (without any body or implementation code). The abstract methods give a template structure of methods from which subclasses can be developed easily. Subclass job is just to override (or give the code) as per its convenience and need not think about the design part (how many methods it should contain, what are they, how they are related etc). Interfaces play a vital role in Java coding and designing modules.

The interface methods can be implemented by various subclasses as per the code appropriate to them. For example, the following "interface Mammal" can be implemented by thousands of mammals as per their nature. Following program is one of the generic implementations.

interface Mammal
{
  String chambers = "4-chambered";
  void offSpring();
  void feed();
  void blood(String str);
}
public class Nature implements Mammal
{
  public void offSpring()
  {
    System.out.println("Only 3 mammals lay eggs and others give birth to young ones");
  }
  public void feed()
  {
    System.out.println("Mammals feed the offspring with milk");
  }
  public void blood(String str)
  {
    System.out.println("Mammals are " + str + " and contains " + cambers + " heart");
  }
  public static void main(String args[])
  {
    Nature n1 = new Nature();
    n1.offSpring();
    n1.feed();
    n1.blood("warm-blooded");
  }
}

[caption id="attachment_355" align="aligncenter" width="515" caption="Output screen of Nature.java"]Interfaces Multiple Inheritance[/caption]

"interface Mammal" includes three methods and one variable. In the method declaration, the keywords public and abstract are omitted as a style and if omitted, we know earlier, they are taken by default. Similarly, the string variable "chambers" is, by default, public, static and final. That is, interface variables cannot be reassigned (as they are implicitly final).

The interface methods offSpring(), feed() and blood(String) can be implemented by different species of animals in different ways as per their nature. The above code is just one example of such implementations.

Compare and Contrast Abstract classes with Interfaces?

Even though the interface is a special derivative of abstract class; it differs a lot with abstract class. Following table gives their differences.

Abstract class

Interface

  1. Multiple inheritance is not supported

Multiple inheritance is supported

2. To inherit "extends" keyword is used

To inherit "implements" keyword is used

3. May include concrete methods also

All must be abstract methods

4. Methods may be of any specifier except private. That is, may be public, protected or default

Methods must be public only

5. Access specifier should be written

If omitted, taken by default (as public)

6. Access modifier abstract should be written

If omitted, taken by default (as abstract)

7. Variables can be any access specifier including private

Variables should be public, static and final. If omitted, taken by default.

8. Constructors can be included in code

No constructors

9. main() can be included in code

main() method cannot be included

Table: Differences between abstract classes and interfaces

After knowing the differences, let us see the similarities.

Similarities between abstract classes and interfaces
  1. With abstract classes and interfaces, objects cannot be created; but reference variables can be created.
  2. All the abstract methods of the both should be overridden by the inherited class.
  3. "Dynamic polymorphism" is supported by both.
  4. Both works as template (structure of methods) from which new classes can be derived easily.

Java Interfaces Multiple Inheritance

Multi-level Inheritance with Two Interfaces

A programmer should be a little careful in using inheritance between two interfaces. It must be "extends" keyword between two interfaces.

interface Reptiles
{
  void size();
}
interface Crocodile extends Reptiles
{
  void amphibian();
}
public class Features implements Crocodile
{
  public void size()
  {
    System.out.println("Reptiles are of small size except crocs and a few snakes and turtles");
  }
  public void amphibian()
  {
    System.out.println("Croc is amphibian");
  }
  public static void main(String args[])
  {
    Features f1 = new Features();
    f1.size();
    f1.amphibian();
  }
}

[caption id="attachment_287" align="alignleft" width="777" caption="Output screen of Features.java"]Interfaces Multiple Inheritance[/caption] Observe the usage of "extends" between the two interfaces Reptiles and Crocodile. The abstract methods of the both are overridden by the Features class. Observe the figure representing above classes.

Interfaces Multiple Inheritance

Multiple Inheritance with Interfaces

There is another way of using interfaces. Interfaces support multiple inheritance. That is, after "extends" keyword, there can be any number of interfaces. This is not possible with abstract classes and concrete classes.

interface Hello1   {  void display1();   }
interface Hello2   {  void display2();   }
interface Hello3 extends Hello1, Hello2      // notice, after extends two interfaces
{  
  void display3();   
}
public class StrangeInheritance implements Hello3
{
  public void display1()  { System.out.println("Display 1");  }
  public void display2()  { System.out.println("Display 2");  }
  public void display3()  { System.out.println("Display 3");  }

  public static void main(String args[])
  {
    StrangeInheritance si1 = new StrangeInheritance();
    si1.display1();	si1.display2();	si1.display3();
  }
}

[caption id="attachment_288" align="aligncenter" width="469" caption="Output screen of StrangeInheritance.java"]Interfaces Multiple Inheritance[/caption] Interface Hello3 extends two interfaces, Hello1 and Hello2. The concrete class StrangeInheritance implements Hello3 and overrides the abstract methods of all the three. Even if one is omitted, it is a compilation error. That is, among interfaces, we can go for multiple inheritance. Following figure gives the details.

Interfaces Multiple Inheritance

The above inheritance can be achieved as follows also.

       public class StrangeInheritance implements Hello1, Hello2, Hello3

Getting Objects of Interfaces

This topic is discussed in Object Casting and Java Dynamic Binding Dynamic Polymorphism.