Chapter 7 Multiple Inheritance
Chapter 7 Multiple Inheritance
Through interfaces
• Multiple Inheritance:
▫ One class extending more than one classes, which
means a child class has two or more parent classes.
▫ Java doesn’t support multiple inheritance
▫ For example class C extends both
classes A and B
▫ We have to use Interface
to implement multiple inheritance
in java
Why multiple inheritance is not supported in java?
}
}
--Output
Compile Time Error
How to implement multiple inheritance in java?
• Introduction to interfaces:
▫ Like a class, an interface can have methods and
variables, but the methods declared in interface are by
default abstract (only method signature, no body).
▫ Interfaces specify what a class must do and not how. It
is the blueprint of the class.
▫ Syntax
interface <interface_name> {
// declare constant fields
// declare methods that are abstract by default.
}
• To declare an interface, use interface keyword. It is
used to provide total abstraction.
• It means all the methods in interface are declared with
empty body and are public and all fields are public,
static and final by default.
• Java 8 allows method declared as default to have
method body.
• A class that implement interface must implement all
the methods declared in the interface.
• To implement interface use implements keyword.
• Why do we use interface ?
▫ It is used to achieve total abstraction.
▫ Since java does not support multiple inheritance in case
of class, but by using interface it can achieve multiple
inheritance .
▫ Interfaces are used to implement abstraction. So the
question arises why use interfaces when we have
abstract classes?
The reason is, abstract classes may contain non-final
variables, whereas variables in interface are final, public
and static.
• Code Example
// A simple interface
interface Player
{
final int id = 10;
int move();
}
To implement an interface we use keyword: implements
Java program to demonstrate working of interface.
// A class that implements interface.
import java.io.*;
class testClass implements in1
{
// A simple interface // Implementing the capabilities of
interface in1 // interface.
public void display()
{
{
// public, static and final System.out.println("Geek");
final int a = 10; }
// Driver Code
// public and abstract
public static void main (String[] args)
void display(); {
} testClass t = new testClass();
t.display();
System.out.println(a);
}
}
--Output
Geek 10
Java program to demonstrate multiple
inheritance through default methods.