Home / Programs / Java Inheritance Example
Programming Example

Java Inheritance Example

👁 3,655 Views
💻 Practical Program
📘 Step by Step Learning
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of the parent object.

Information & Algorithm

This is an example of inheritance in Java. The Programmer class is a subclass of the Employee class and inherits its salary field. In addition, the Programmer class has its own field bonus.

When the main method is executed, a new Programmer object is created and its salary and bonus fields are printed to the console. Since salary is inherited from Employee, it has a default value of 40000, and bonus has a value of 10000.

Program Code

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Output

 Programmer salary is:40000.0
 Bonus of programmer is:10000

Explanation

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.