Hierarchical Inheritance Example
This program demonstrates hierarchical inheritance.
Problem Statement
Write a Java program to show hierarchical inheritance with multiple subclasses.
Source Code
| 1 | class Person { |
| 2 | String name; |
| 3 | } |
| 4 | class Student extends Person { |
| 5 | int age; |
| 6 | } |
| 7 | class Teacher extends Person { |
| 8 | String subject; |
| 9 | } |
| 10 | public class HierarchicalInheritance { |
| 11 | public static void main(String[] args) { |
| 12 | System.out.println("Eduinq Hierarchical Inheritance"); |
| 13 | Student s=new Student(); |
| 14 | s.name="Arun"; s.age=20; |
| 15 | Teacher t=new Teacher(); |
| 16 | t.name="Rahul"; t.subject="Math"; |
| 17 | System.out.println("Student: "+s.name+", Age: "+s.age); |
| 18 | System.out.println("Teacher: "+t.name+", Subject: "+t.subject); |
| 19 | } |
| 20 | } |
Program Output
Eduinq Hierarchical Inheritance Student: Arun, Age: 20 Teacher: Rahul, Subject: Math
Explanation
Multiple subclasses inherit from same superclass. - Student and Teacher both extend Person. - This demonstrates hierarchical inheritance structure. Conclusion: Shows how to implement hierarchical inheritance.