Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào để chuyển đổi một biến lớp con thành một kiểu siêu lớp trong Java?

Kế thừa là quan hệ giữa hai lớp trong đó một lớp kế thừa các thuộc tính của lớp kia. Mối quan hệ này có thể được xác định bằng cách sử dụng từ khóa mở rộng là -

public class A extends B{

}

Lớp kế thừa các thuộc tính được gọi là lớp con hoặc lớp con và lớp có các thuộc tính được kế thừa là lớp siêu hoặc, lớp cha.

Trong kế thừa, một bản sao của các thành viên siêu lớp được tạo ra trong đối tượng lớp con. Do đó, bằng cách sử dụng đối tượng lớp con, bạn có thể truy cập các thành viên của cả hai lớp.

Chuyển đổi một biến lớp con thành một kiểu siêu lớp

Bạn có thể gán trực tiếp một biến lớp con (giá trị) vào một siêu biến. Nói tóm lại, biến tham chiếu siêu lớp có thể chứa đối tượng lớp con. Tuy nhiên, bằng cách sử dụng tham chiếu này, bạn chỉ có thể truy cập vào các thành viên của lớp siêu cấp, nếu bạn cố gắng truy cập vào các thành viên lớp con, lỗi thời gian biên dịch sẽ được tạo ra.

Ví dụ

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();
   }
}

Đầu ra

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

Ví dụ

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();
   }
}

Đầu ra

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