Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 하위 클래스 변수를 상위 클래스 유형으로 변환하는 방법은 무엇입니까?

<시간/>

상속 한 클래스가 다른 클래스의 속성을 상속하는 두 클래스 간의 관계입니다. 이 관계는 extends 키워드를 사용하여 -

로 정의할 수 있습니다.

public class A extends B{

}

속성을 상속하는 클래스를 하위 클래스 또는 하위 클래스라고 하고 속성을 상속받는 클래스를 상위 클래스 또는 상위 클래스라고 합니다.

상속에서 상위 클래스 구성원의 복사본이 하위 클래스 개체에 생성됩니다. 따라서 하위 클래스 개체를 사용하여 두 클래스의 구성원에 액세스할 수 있습니다.

하위 클래스 변수를 상위 클래스 유형으로 변환

하위 클래스 변수(값)를 상위 변수에 직접 할당할 수 있습니다. 요컨대, 상위 클래스 참조 변수는 하위 클래스 객체를 보유할 수 있습니다. 그러나 이 참조를 사용하면 상위 클래스의 구성원에만 액세스할 수 있으며 하위 클래스 구성원에 액세스하려고 하면 컴파일 시간 오류가 생성됩니다.

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