Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

จะแปลงตัวแปรคลาสย่อยเป็นประเภท super class ใน Java ได้อย่างไร?


มรดก เป็นความสัมพันธ์ระหว่างสองคลาสโดยที่คลาสหนึ่งสืบทอดคุณสมบัติของคลาสอื่น ความสัมพันธ์นี้สามารถกำหนดได้โดยใช้คีย์เวิร์ดขยายเป็น −

public class A extends B{

}

คลาสที่สืบทอดคุณสมบัติเรียกว่าคลาสย่อยหรือคลาสย่อยและคลาสที่มีคุณสมบัติที่สืบทอดมาคือ super class หรือ parent class

ในการสืบทอด สำเนาของสมาชิก super class จะถูกสร้างขึ้นในวัตถุคลาสย่อย ดังนั้น การใช้อ็อบเจ็กต์คลาสย่อย คุณสามารถเข้าถึงสมาชิกของทั้งสองคลาสได้

การแปลงตัวแปรคลาสย่อยเป็นประเภทซูเปอร์คลาส

คุณสามารถกำหนดตัวแปรคลาสย่อย (ค่า) ให้กับตัวแปรระดับสูงได้โดยตรง กล่าวโดยสรุป ตัวแปรอ้างอิง super class สามารถเก็บอ็อบเจ็กต์ย่อยได้ แต่โดยใช้ข้อมูลอ้างอิงนี้ คุณจะเข้าถึงสมาชิกของ super class ได้เท่านั้น หากคุณพยายามเข้าถึงสมาชิกคลาสย่อย ข้อผิดพลาดในการคอมไพล์จะถูกสร้างขึ้น

ตัวอย่าง

class Person{
   public String name;
   public int age;
   public Person(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void displayPerson() {
      System.out.println("Data of the Person class: ");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
   }
}
public class Sample extends Person {
   public String branch;
   public int Student_id;
   public Sample(String name, int age, String branch, int Student_id){
   super(name, age);
      this.branch = branch;
      this.Student_id = Student_id;
   }
   public void displayStudent() {
      System.out.println("Data of the Student class: ");
      System.out.println("Name: "+super.name);
      System.out.println("Age: "+super.age);
      System.out.println("Branch: "+this.branch);
      System.out.println("Student ID: "+this.Student_id);
   }
   public static void main(String[] args) {        
      Person person = new Person("Krishna", 20);      
      //Converting super class variable to sub class type
      Sample sample = new Sample("Krishna", 20, "IT", 1256);      
      person = sample;
      person.displayPerson();
   }
}

ผลลัพธ์

Data of the Person class:
Name: Krishna
Age: 20

ตัวอย่าง

class Super{
   public Super(){
      System.out.println("Constructor of the Super class");
   }
   public void superMethod() {
      System.out.println("Method of the super class ");
   }
}
public class Test extends Super {
   public Test(){
      System.out.println("Constructor of the sub class");
   }
   public void subMethod() {
      System.out.println("Method of the sub class ");
   }
   public static void main(String[] args) {        
      Super obj = new Test();  
      obj.superMethod();
   }
}

ผลลัพธ์

Constructor of the Super class
Constructor of the sub class
Method of the super class