Interface

Interface:
  • It consist of abstract, static and default methods
  • It is created using interface keyword
  • It consist of only public static final data members
  • Class could extends another class but implements interfaces
  • Those class who implements an interface have to provide implementations of all the abstract methods 
  • It can also have main method
  • It can not have Constructor

Advantage of Interface:
  • Supports Multiple inheritance
  • Method implementation restriction
  • Code re-usability through static and default method
Syntax:
AcessSpecifiers interface InterfaceName {
     //Constant data members
     //abstract, static and defaults methods
}

Example: Create an interface Jet and a class Aeroplane that implements Jet interface?

Jet.java
package com.java.iter;

public interface Jet {
    int id = 10;
    void start();
    void fly();
    void stop();

    static void takeof(){
        System.out.println("Jet is taking off");
    }
    default void landing(){
        System.out.println("Jet is landing");
    }
    public static void main(String[] args) {
        System.out.println("Data member Id of interface Jet is " + id);
        Jet.takeof();
    }
}

Output:
Data member Id of interface Jet is 10
Jet is taking off

Aeroplane.java
package com.java.iter;

public class Aeroplane implements Jet {
    public void start() {
        System.out.println("Aeroplane is sarting");
    }
    public void fly() {
        System.out.println("Aeroplane is flying");
    }
    public void stop() {
        System.out.println("Aeroplane is stoping");
    }
    public static void main(String[] args) {
        //Jet j = new Jet();            //compiler error because interface cannot be instantiated
        Aeroplane a = new Aeroplane();
        a.start();
        Jet.takeof();
        a.fly();
        a.landing();
        a.stop();
        System.out.println("Id of interface Jet is " + a.id);
        System.out.println("Id of interface Jet is "+Jet.id);
        //a.id = 30;        //Compiler error because interface data members are final
    }
}

Output:
Aeroplane is sarting
Jet is taking off
Aeroplane is flying
Jet is landing
Aeroplane is stoping
Id of interface Jet is 10
Id of interface Jet is 10

No comments:

Post a Comment