Interface

An interface is an abstract class that is used to group related methods with empty bodies, Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces

Uses of Interface

- It is used to achieve loose coupling which means dependencies of a class that uses another class are highly reduced. In simple the main class has access to the classes that are exposed through the interface
- Interfaces are used to implement abstraction. The reason is, that abstract classes may contain non-final variables, whereas variables in the interface are final, public, and static.
- Interface can used to implement Inheritance

Syntax for interface

 Syntax to declare interface is as follows

interface {
     // declare constant fields
    // declare methods that abstract
    // by default.
}

 

Interface is the keyword used to declare it and all fields are public, static, and final by default. To implement an interface implement keyword is used. A class can implement more than one interface. An interface can extend to another interface (but only one interface). A class that implements the interface must implement all the methods in the interface.

Use case demonstrating the interface

 
interface MySample {
    public void method1();
    public void method2();
}
public class Demo implements MySample {
    /* This class must have to implement both the abstract methods
     * else you will get compilation error
     */
    public void method1() {
        System.out.println("implementation of method1");
    }
    public void method2() {
        System.out.println("implementation of method2");
    }
    public static void main(String arg[]) {
        MySample s = new Demo();
        s.method1();
    }
}

 

Output:

 implementation of method1
 
 

Related Tutorials

Map