Interface in java:
interface is a blueprint of class in java that is used to define contracts. It can contain static constant and abstract method. Interface is used in java for achieving abstraction. With the help of interface we can achieve multiple Inheritance. Till java 7 we can't create methods with body. All the methods will be abstract public.
In java 8 we can create default and static methods with body.
In java 9 we can create private method also.
Uses of Interface:
1. For achieving multiple Inheritance.
2. For achieving loose coupling.
3. For achieving abstraction.
4. Interface is used for abstraction.Many people thinks that why we use interface when we have abstract class. Abtract class is heavy weight as it can contain non-final variable,non-abstract method,constructors alos but Interface methods are public abstract and all variables are public static final.
How to declare an interface?
import java.lang.*; // Any number of import statements public interface NameOfInterface { // Any number of final, static fields // Any number of abstract method declarations\ }
New Features in JDK8 Interface:
Java 8 Default Method in Interface:
// An example to show that interfaces can // have default methods from JDK 1.8 onwards interface In1 { final int a = 10; default void display() { System.out.println("Default Method"); } } // A class that implements the interface. class MainClass implements In1 { public static void main (String[] args) { MainClass t = new MainClass(); t.display(); } }
Default Method
Java 8 Static Method in Interface:
// An example to show that interfaces can // have static methods from JDK 1.8 onwards interface In1 { final int b = 10; static void message() { System.out.println("Static Method"); } } // A class that implements the interface. class MainClass implements In1 { public static void main (String[] args) { In1.message();
} }
Static Method
New Features in JDK9 Interface:
Marker or tagged interface:
public interface Serializable { // Empty,no fields and no methods }
Serializable interface:
Implementing Interfaces:
interface Printable{ void print(); } class Test implements Printable{ public void print(){System.out.println("Printing Data");} public static void main(String args[]){ Test obj = new Test();
obj.print(); } }
Printing Data