Java Inheritance Part 1: Inheriting Public Members

Inheritance:

Inheritance is a process where one class acquires the properties (variable and methods) of another class.

Importance:

  • For code reusability.
  • For method overloading.
  • Implement parent-child relationship.


Code:

  1. // Base class  
  2.   
  3. public class StudentI {  
  4.       
  5.     int id;  
  6.     String name;  
  7.     String dept;  
  8.       
  9.     public void dispInfo() {  
  10.         System.out.println("Id : "+id);  
  11.         System.out.println("Name : "+name);  
  12.         System.out.println("Department : "+dept);  
  13.     }  
  14.   
  15. }  
  16.   
  17. // Derived class  
  18.   
  19. public class TeacherI extends StudentI { //inherit class studenti  
  20.       
  21.     int age;  
  22.       
  23.     public void disp() {  
  24.         dispInfo();  
  25.         System.out.println("Age : "+age);  
  26.     }  
  27.   
  28. }  
  29.   
  30. // Main class  
  31.   
  32.   
  33. public class InheritanceDemo {  
  34.   
  35.     public static void main(String[] args) {  
  36.         // TODO Auto-generated method stub  
  37.           
  38.         StudentI s1=new StudentI();  
  39.         s1.id=1001;  
  40.         s1.name="Sujan Hasan";  
  41.         s1.dept="CSE";  
  42.         s1.dispInfo();  
  43.         System.out.println();  
  44.           
  45.         StudentI s2=new StudentI();  
  46.         s2.id=1002;  
  47.         s2.name="Shakil Sorker";  
  48.         s2.dept="CSE";  
  49.         s2.dispInfo();  
  50.         System.out.println();  
  51.           
  52.         TeacherI t1=new TeacherI();  
  53.         t1.id=7001;  
  54.         t1.name="Alamgir Hossain";  
  55.         t1.dept="CSE";  
  56.         t1.age=30;  
  57.         t1.disp();  
  58.         System.out.println();  
  59.           
  60.         TeacherI t2=new TeacherI();  
  61.         t2.id=7003;  
  62.         t2.name="Shamol Pal";  
  63.         t2.dept="CSE";  
  64.         t2.age=37;  
  65.         t2.disp();  
  66.         System.out.println();  
  67.           
  68.   
  69.     }  
  70.   
  71. }  
Share:

0 Comments:

Post a Comment