The following example demonstrates Implementing Inheritance in Java.

Basically, inheritance enables a class to inherit the properties and methods of its parent class. The following example demonstrates inheritance. Here, we have a class Person having a single attribute name that represents the name of a person. Also, the Person class has getter and setter methods for the name attribute. The class Employee is a subclass of the Person class. Additionally, it declares three attributes of its own – annual_salary, year_started, and insurance_number. It defines the getter and setter methods. Further, it initializes the attributes of objects using a parameterized constructor.

Since we need to call the base class constructor also for initializing the name attribute, we use the super keyword. Finally, we define the TestEmployee class that instantiates the Employee class.

Person.java

public class Person {
	String name;

	public Person(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}	
}

Employee.java

public class Employee extends Person {
	double annual_salary;
	int year_started;
	String insurance_number;
	public Employee(String name, double annual_salary, int year_started, String insurance_number) {
		super(name);
		this.annual_salary = annual_salary;
		this.year_started = year_started;
		this.insurance_number = insurance_number;
	}
	public double getAnnual_salary() {
		return annual_salary;
	}
	public void setAnnual_salary(double annual_salary) {
		this.annual_salary = annual_salary;
	}
	public int getYear_started() {
		return year_started;
	}
	public void setYear_started(int year_started) {
		this.year_started = year_started;
	}
	public String getInsurance_number() {
		return insurance_number;
	}
	public void setInsurance_number(String insurance_number) {
		this.insurance_number = insurance_number;
	}	
}

TestEmployee.java

public class TestEmployee {

	public static void main(String[] args) {
		Employee emp_ob=new Employee("Raman", 37500.0, 2011, "201167678924");
		System.out.println("Employee Details...");
		System.out.println("Employee Name: "+emp_ob.getName());
		System.out.println("Annual Salary: "+emp_ob.getAnnual_salary());
		System.out.println("Year Started: "+emp_ob.getYear_started());
		System.out.println("Insurance Number: "+emp_ob.getInsurance_number());
	}
}

Output

A Program for Implementing Inheritance in Java
A Program for Implementing Inheritance in Java

Further Reading

Java Practice Exercise

programmingempire

Princites