Interface
Interface
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.
1interface Suzuki
2{
3 public abstract void body();
4}
5interface Ford
6{
7 public abstract void engine();
8}
9public class MotorCar implements Suzuki, Ford
10{
11 public void body()
12 {
13 System.out.println("Fit Suzuki body");
14 }
15 public void engine()
16 {
17 System.out.println("Fit Ford engine");
18 }
19 public static void main(String args[])
20 {
21 MotorCar mc1 = new MotorCar();
22 mc1.body();
23 mc1.engine();
24 }
25}
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.
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.
1interface Mammal
2{
3 String chambers = "4-chambered";
4 void offSpring();
5 void feed();
6 void blood(String str);
7}
8public class Nature implements Mammal
9{
10 public void offSpring()
11 {
12 System.out.println("Only 3 mammals lay eggs and others give birth to young ones");
13 }
14 public void feed()
15 {
16 System.out.println("Mammals feed the offspring with milk");
17 }
18 public void blood(String str)
19 {
20 System.out.println("Mammals are " + str + " and contains " + cambers + " heart");
21 }
22 public static void main(String args[])
23 {
24 Nature n1 = new Nature();
25 n1.offSpring();
26 n1.feed();
27 n1.blood("warm-blooded");
28 }
29}
Output screen of Nature.java
Abstract class I