1.

Write a program in Java to show multiple inheritance.

Answer»

Multiple inheritance is not possible in Java. So, we can use Interfaces in Java to create a scenario of multiple inheritance. In our example below, we have a class called Phone and a class called SmartPhone. We know that a SmartPhone is a Phone, however, it has various other features as well. For instance, a SmartPhone has a camera, a music player, etc. Notice that a SmartPhone is a Phone and has a camera and has a Music Player. So, there is one is-A relationship and multiple has-A relationships. The is-A relationship denotes extending the features and the has-A relationship denotes implementing the features. This means that a SmartPhone is a Phone i.e. it extends the features of a Phone however, it just implements the features of a Music Player and a Camera. It itself is not a music player or a camera. Following is the code for the above discussion.

Java Code for Multiple Inheritance

public class Main {
public static void main(String[] args) {

SmartPhone sp1 = new SmartPhone();
Phone p1 = new SmartPhone();

ICamera c1 = new SmartPhone();
IMusicplayer m1 = new SmartPhone();

sp1.videocall();
p1.call();
p1.message();
c1.click();
c1.record();
m1.play();
m1.pause();
m1.stop();

}
}

class Phone {

void call() {
System.out.println("call");
}

void message() {
System.out.println("Message");
}
}

interface ICamera {

void click();

void record();
}

interface IMusicplayer {
void play();

void pause();

void stop();
}

class SmartPhone extends Phone implements ICamera, IMusicplayer {

void videocall() {
System.out.println("Video call");
}

@Override
public void click() {
System.out.println("Picture click");
}

@Override
public void record() {
System.out.println("Record video");
}

@Override
public void play() {
System.out.println("Play music");
}

@Override
public void pause() {
System.out.println("Pause Music");
}
@Override
public void stop() {
System.out.println("Stop music");
}

Output

Video call
Call
Message
Picture click
Record Video
Play music
Pause Music
Stop music


Discussion

No Comment Found