In Java programming, an interface is a collection of method declaration and constant that one or more class can use.
It is syntactically similar to the class but the main difference between class and interface is that class contain method declaration with method body and interface method declares without any body.
Syntax of interface:
1 2 3 4 5 6 7 8 9 10 11 | access specifier interface InterfaceName { type var1 = value; type var2 = value; ..... .... type method1(parameter list); type method2(parameter list); } |
- Access modifier is always public which indicates that the interface can be used by any class.
- To declare the class as an interface, interface keyword is used.
- Variables declares inside the interface are implicitly final and static. They can’t be changed in the implementing class.
- All methods in the interface are the implicitly abstract method.
- The main difference between class and interface is that class contains method with method body and interface contains only abstract method.
Implementing an Interface
Once the interface has been defined, one or more classes can
Syntax for implementing interface:
1 2 3 | class className implements interface1, interface2,....interfaceN{ } |
Multiple inheritance: Java dose not support multiple inheritance.
Let A and B are parent class and C is the derived class. In Java, instead of multiple inheritances we use interface.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | interface Sum { int z = 30; // interface variable public void add(); // interface method declaration } class A { int x, y; void set(int a, int b) { x = a; y = b; } } class B extends A implements Sum { int sum; public void add() { sum = x + y + z; // x,y are the variable of class A & z is a variable of interface f System.out.println("sum=" + sum); } } public class Test { public static void main(String arg[]) { B obj = new B(); obj.set(10, 20); obj.add(); } } |
Result
1 | sum=60 |