In this section we will learn about how to create interface and how to declare interface in Java.
Interface in Java
Interface in java programming languages is a collection of abstract methods. A class must implements interface. An interfaces are declared using interface keyword. The variable inside interface are by default static and final. Interface is one of the core feature of Object oriented concept. Through interface only abstraction is achieved in java.
Syntax for declaring Interface:
access-modifier interface interface_name [extends other interface] { constant declaration abstract methods declaration }
To use an interface in a class append implement keyword followed by class name followed by interfacename. Some of the key point of interface as follows:
- With the help of Interface fully abstraction is achieved in Java.
- In an interface, only abstract method can be declared.
- Interface is used to support multiple inheritance.
- All variable declared inside interface is by default final.
- All method inside interface is by default public and abstract. If you do not define method as public or abstract compiler implicitly treated as public abstract.
- An interface can extends multiple interface.
- An interface is only implemented by a class not extended by a class.
- Method inside interface is ended with semicolon, because method implementation is not allowed only declaration.
- An interface doesn't contain any constructor.
- An interface is implicitly abstract you do not need to use abstract keyword when declaring an interface.
Example :
interface Y { int a = 2; public void display(); } public class X implements Y { public void display() { System.out.println("Variable of interface = " + a); } public static void main(String args[]) { X ob = new X(); ob.display(); } }
Output of the program as follows:
Multiple inheritance by interface
In Java a class can extend only one class but a interface can extends multiple interface. Now, here is the example extending multiple interface in Java
interface X { void show(); } interface Y { void show1(); } interface Z extends X, Y { void display(); } public class YY implements Z { public void show() { System.out.println("Method of Interface X"); } public void show1() { System.out.println("Method of Interface Y"); } public void display() { System.out.println("Method of Interface Z"); } public static void main(String args[]) { YY ob = new YY(); ob.display(); ob.show(); ob.show1(); } }
Output of the program: