Interface in Java
Java Interface
Interfaces are like reference for the implementation of real time entities(class). Interface will have the methods and variables. The class implementing interface should use a keyword implements.
Note: Till java 1.7 – methods are abstract, public and variables are public, final, static.
Example: Mobile is the interface and the real time implementation of the interfaces will be done by the mobile manufactures.
interface Mobile{ int i=10; public void call(); public void messaging();} class SamsungS10 implements Mobile{ public void call(){ System.out.println(“call implementation”); } public void messaging(){ System.out.println(“messaging implementation”); } } |
From java 1.8 interfaces can have default methods and static methods
Default methods:
interface Mobile{ int i=10; public void call(); public void messaging(); default void unlockMobile(){ System.out.println(“pattern”); } } |
No need of implementation of unlockMobile method:
class Lenovop1 implements Mobile{ public void call(){ System.out.println(“call implementation”); } public void messaging(){ System.out.println(“messaging implementation”); } } |
Implementing unlockMobile() method:
class Lenovop1 implements Mobile{ public void call(){ System.out.println(“call implementation”); } public void messaging(){ System.out.println(“messaging implementation”); } public void unlockMobile(){ System.out.println(“pattern or thumb impression”); } } |
Static Methods:
Same as default methods except we can call static methods by interface name directly.
interface Mobile{ int i=10; public void call(); public void messaging(); static void unlockMobile(){ System.out.println(“pattern”); } } Class User{ public static void main(String[] args){ Mobile.unlockMobile(); } } |
interface InterfaceA{ default void defaultMethod(){ System.out.println(“interfaceA default method”) } } interface InterfaceB{ default void defaultMethod(){ System.out.println(“interfaceB default method”) } } class ImplementationClass implements InterfaceA,InterfaceB{ public void normalMethod(){ System.out.println(“normal method”); } } class MainClass { public static void main(String[] args){ ImplementationClass objImplementationClass = new ImplementationClass(); objImplementationClass.defaultMethod(); } } |
Solution : Need to implement the default method or the static method in the implementation class when we are implementing two interfaces which have same signature for the default or static methods.