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 understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.