1.

Write a program in Java to show inheritance in Java.

Answer»

This program is for testing the concepts of inheritance in Java and the usage of extends keyword. Following is an example program in which a class SmartPhone extends a class Phone. This is a real-life example as a phone has basic features of calling and messaging whereas a smartphone has several other features like clicking pictures, playing music, etc. 

Java Code for showing Inheritance

class Phone {
private int number;

Phone() {

}

void setNumber(int number) {
this.number = number;
}

int getNumber() {
return number;
}

public void call() {
System.out.println("Call is made");
}

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

}

class SmartPhone extends Phone {

int cameraMegaPX;

public void click() {
System.out.println("A photograph was clicked");
}

public void playMusic() {
System.out.println("Music Started Playing");
}

public void pauseMusic() {
System.out.println("Music Paused");
}

public void stopMusic() {
System.out.println("Music Stopped");
}
}

class Main {
public static void main(String args[]) {
// Your code goes here

SmartPhone p1 = new SmartPhone();
p1.setNumber(9863472);
System.out.println("Phone number is: " + p1.getNumber());
p1.call();
p1.playMusic();
}

Sample Output

Phone number is: 9863472
Call is made
Music Started Playing


Discussion

No Comment Found