DEV Community

Cover image for Interface In JAVA & Multiple Inheritance
Gourav Kadu
Gourav Kadu

Posted on

Interface In JAVA & Multiple Inheritance

MULTIPLE INHERITANCE

*Lets Understand what multiple inheritance is *
Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class.
Inheritance-sm.jpg

as shown in above figure in multiple inheritance child class can have 2 or more base class to achieve this we need INTERFACE.

INTERFACE

An interface in Java is a blueprint of a class. It has static constants and abstract methods.
i.e. An Interface can only contain abstract methods() and variables, it cannot have body of a method.
It cannot be instantiated just like the abstract class.

  • So where do we declare the body of these methods??

    The body of method is declared inside a class where the method is needed according to the programmer's requirement.

  • How to declare and interface?

    Interface is declared using interface keyword
    Syntax :
    interface interface_name{ abstract methods}

  • Note

    To use declared interface in class we need to use implements keyword

Implementation

First we will create a interface "print" and inside it we will create a abstract method print();

interface printgib{
void print();
}
Enter fullscreen mode Exit fullscreen mode

Now we got our interface ready to be used by classes so lets create classes abc and gk and implement interface in it.


public class abc implements printgib{
public void print(){                     //1st implementation of print 
System.out.println("I love you 3000"); 
}
public static void main(String[] args){
abc obj = new abc();
gk obj1 = new gk();
obj.print();
obj1.print();
}
}

class gk implements printgib{
public void print(){                   //2nd implementation of print 
System.out.println("I am Gk");
}
}
Enter fullscreen mode Exit fullscreen mode

as shown in above code we achieved multiple inheritance and implemented interface.

  • Now to run the code save the file and
javac file_name.java
Enter fullscreen mode Exit fullscreen mode
java abc
Enter fullscreen mode Exit fullscreen mode

Output:-

image.png

Top comments (0)