Interfaces and Inheritance in Java

Interfaces and Inheritance in Java

The main difference between interfaces and inheritance is that a class cannot inherit more than one classes (multiple inheritance is not allowed in Java). Still, a class can implement more than one interface.

Sample Program

The following program demonstrates how a class can implement multiple interfaces.

import java.io.*;
interface intfA
{
void m1 ();
}
interface intfB
{
void m2 ();
}
class Sample implements intfA, intfB
{
@Override
public void m1()
{
System.out.println (“Welcome: inside the method m1”);
}
@override
public void m2()
{
System.out.println (“Welcome: Inside the method m2”);
}
}
class Demo
{
public static void main (String args [])
{
Sample obj = new Sample ();
obj.m1();
obj.m1();
}
}

 

OUTPUT

Welcome: inside the method m1

Welcome: inside the method m2

 

Interface Inheritance

This feature bridges the gap between interfaces and inheritance. Java allows one interface to extend another interface. A class can thereafter implement the whole structure.

Sample Code

This code demonstrates the inheritance of interfaces in Java.

import java.io.*;
interface intfA
{
void name();
}
interface intfB extends intfA
{
void institute();
}
class sample implements intfB
{
@Override
public void name()
{
System.out.println (“Rohit”);
}
@Override
public void institute ()
{
System.out.println (“IIT”);
}
public static void main (String args [])
{
sample obj = new sample ();
obj.name();
obj.institute();
}
}

 

OUTPUT

IIT

Interfaces can extend multiple interfaces

import java.io.*;
interface intfA
{
void name();
}
interface intfB
{
void institute ();
}

interface intfC extends intfA, intfB
{
void branch();
}
class sample implements intfC
{
public void name()
{
System.out.println (“Rohit”);
}
public void institute ()
{
System.out.println (“IIT”);
}
public void branch()
{
System.out.println (“CSE”);
}
public static void main (String args [])
{
sample obj1 = new sample();
obj.name();
obj.institute();
obj.branch();
}
}

 

OUTPUT

Rohit
IIT
CSE

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.