Programming

Java – Extends Keyword for Inheritance

In inheritance, the base class inherits the superclass.

To inherit a class in Java extends keyword is used in the subclass definition to inherit a superclass.

Create two Java class first: MyInfo, second is FullInfo extends from MyInfo. This means FullInfo will inherit information from MyInfo class. Inheritance is used to do work faster.

Here don’t need to create an unnecessary class to collect information from superclass and display.

Java Source 1

public class MyInfo {
private String name;
public void setName(String n) {
name=n;
}
public void getName(){
System.out.println("Name::"+name);
}
}

Java Source 2

public class FullInfo extends MyInfo{
private String address;
private double ph;
public void setData(String aa, double p){
address = aa;
ph = p;
}
public void getData(){
System.out.println("Address::"+address);
System.out.println("Phone::"+ph);
}
public static void main(String[] args) {
FullInfo x= new FullInfo();
x.setName("Satya Joshi");
x.getName();
x.setData("Kathmandu",48729336);
x.getData();
}
}

Output

Name::Satya Joshi
Address::Kathmandu
Phone::729336

Tuts

About Author

Tutsmaster.org provides tutorials related to tech and programmings. We are also setting up a community for the users and students.