DEV Community

nantha kumar
nantha kumar

Posted on

Interface

What is interface :

  1. An interface is a set of rules.

Simple Definition :

  1. An interface tells a class what to do, not how to do it.

Why used interface :

  1. It is used to achieve 100% abstraction and multiple inheritance.

  2. To define common behavior across different classes

Notes :

  1. An interface contains only abstract method.

  2. All methods are public and abstract by default in interface.

  3. All variables are public static final in interface.

  4. We can't create object for interface.

  5. We can't create constructor in interface.

After java 8th version :

Default Methods :

  1. We can create method with body in interface using default keyword.

Static Methods :

  1. We can create static method using static keyword in interface.

  2. We can call the static method using interface name.

  3. We can't override the static method.

Multiple Inheritance Problem Solved :

interface A {
    default void show() {
        System.out.println("A");
    }
}

interface B {
    default void show() {
        System.out.println("B");
    }
}

class Test implements A, B {
    @Override
    public void show() {
        A.super.show();   // calls A's default method
        // B.super.show(); // you can call this also if needed
    }

    public static void main(String[] args) {
        Test t = new Test();
        t.show();
    }
}
Enter fullscreen mode Exit fullscreen mode

Private Methods (Java 9+) :

  1. private method used to reuse code inside interface.

  2. Can't accessed by implementing classes.

Top comments (0)