Syntax
access-modifier interface InterfaceName { //constants and method declarations }
interface Father { int f = 1; void printFather(); } interface Child extends Father { int c = 2; void printChild(); } class GrandSon implements Child { public void printFather() { System.out.println("f = "+f); } public void printChild() { System.out.println("c = "+c); } public static void main(String args[]) { GrandSon g = new GrandSon(); g.printFather(); g.printChild(); } }
Output
f = 1 c = 2
In Java, you can achieve multiple inheritance with the help of interface. A class can implement one or more interface and an interface can extend one or more interface.
interface Father { int f = 1; void printFather(); } interface Mother { int m = 2; void printMother(); } interface Child extends Father, Mother { int c = 3; void printChild(); } class GrandSon implements Child { public void printFather() { System.out.println("f = "+f); } public void printMother() { System.out.println("m = "+m); } public void printChild() { System.out.println("c = "+c); } public static void main(String args[]) { GrandSon g = new GrandSon(); g.printFather(); g.printMother(); g.printChild(); } }
Output
f = 1 m = 2 c = 3
abstract Class | Interface |
---|---|
An abstract class may or may not have abstract method. | All the methods inside an interface are by default abstract. |
An abstract class can contain constructor. | You cannot define constructor in an interface. |
In an abstract class, the data variable may or may not be defined constant. | An interface can only have constants. |
It supports single level inheritance. | It supports multiple inheritance. |