Home Java Programming Language / Programs / Java Inheritance Example
🚀 Programming Example

Java Inheritance Example

👁 3,657 Views
💻 Practical Program
📘 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);
}
}
                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

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.

🔥 Practice suggestion

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.