Java Inheritance Example

Java Programming Language Inheritance in java (Article) Inheritance in java (Program)

3559

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:

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.


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.