Java Interface | Java example

 

Java Interface :

Java Interface is used to achieve abstraction.In previous tutorial we have seen inheritance and types of inheritance.

There are two more inheritance concepts which we did not discussed previously because they can be only achieved only through interfaces.

To make it more simpler way when you declare a class you cannot extend multiple classes to it

java interface

So i think you understand the concept of interfaces, we can implement more than one interface to a class.

 

Multiple Inheritance:

To explain interface the best way is to show a multiple inheritance now let us consider we have to implement two interface in our class to achieve oyr requirements

 

Declare one interface and add a abstract method

interface A{

    void display();
}

 

now consider one more interface

interface B{

    void alert();
}

 

Now we can implement both the interfaces in our class

class GetInterface implements A,B{


    @Override
    public void display () {

        System.out.println("Display");
    }

    @Override
    public void alert () {

        System.out.println("Alert");
    }

    public static void main(String args[]) {

        GetInterface g = new GetInterface();
        g.display();
        g.alert();

    }
}

 

java interface

 

Hybrid Inheritance:

Hybrid inheritance is achieved only through interfaces but not using java classes.

Now consider a student details class we are having each detail in separate interface to demonstrate a hybrid inheritance.

Hybrid inheritance is a combination of two inheritance like multilevel and hierarchical inheritance.

 

interface for student id

interface A{

    void id();
}

 

interface for student name extending interface a

interface B extends A{

    void name();
}

 

interface for student course extending interface a

interface C extends A{

    void course();
}

 

now we will achieve hybrid inheritance by implementing interfaces B,C

public class HybridInheritance implements B,C{
    @Override
    public void id() {

        System.out.println("Student id : 01");
    }

    @Override
    public void name() {

        System.out.println("Student name : Abhi");
    }

    @Override
    public void course() {

        System.out.println("Student course : Computers");

    }

    public static void main(String args[]){

        HybridInheritance h = new HybridInheritance();
        h.id();
        h.name();
        h.course();
    }
}

 

java interface

 

If you are having any query’s on java interface let us know in comment section below.

Show Buttons
Hide Buttons
Read previous post:
Java Inheritance | Java example

  Java Inheritance : Inheritance is acquiring the properties of parent class in child class. Re-usability is the important aspect...

Close