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.
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);
}
}
Programmer salary is:40000.0 Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.