상속(Inheritance)은 한 클래스가 다른 클래스의 속성과 기능을 물려받는 두 클래스 사이의 관계를 의미합니다. 이러한 관계는 extends 키워드를 사용하여 다음과 같이 정의할 수 있습니다.
public class A extends B {
}
속성을 상속받는 클래스를 하위 클래스(sub class) 또는 자식 클래스(child class)라고 하며, 속성을 물려주는 클래스를 상위 클래스(super class) 또는 부모 클래스(parent class)라고 합니다.
상속 관계에서는 하위 클래스 객체가 생성될 때 상위 클래스 멤버들의 복사본이 함께 만들어집니다. 따라서 하위 클래스 객체를 통해 상위 클래스와 하위 클래스 양쪽의 멤버에 모두 접근할 수 있습니다.
상위 클래스 참조 변수를 하위 클래스 타입으로 변환하기
상위 클래스 변수를 하위 클래스 타입으로 변환하려면 캐스트 연산자(cast operator)를 사용하면 됩니다. 단, 변환 작업을 수행하기 전에 반드시 하위 클래스 객체를 이용해 상위 클래스 타입의 참조 변수를 먼저 생성한 후, 이 참조 변수를 캐스트 연산자를 사용하여 하위 클래스 타입으로 변환해야 합니다.
예제 1
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 Sample("Krishna", 20, "IT", 1256);
//Converting super class variable to sub class type
Sample obj = (Sample) person;
obj.displayPerson();
obj.displayStudent();
}
}
출력 결과
Data of the Person class: Name: Krishna Age: 20 Data of the Student class: Name: Krishna Age: 20 Branch: IT Student ID: 1256
위 예제에서 Sample 클래스는 Person 클래스를 상속받습니다. main 메서드에서는 하위 클래스인 Sample 객체를 생성하여 상위 클래스 타입인 Person 참조 변수에 할당한 뒤, 캐스트 연산자 (Sample)을 사용해 이를 다시 하위 클래스 타입으로 변환하고 있습니다. 변환된 객체를 통해 상위 클래스의 displayPerson() 메서드와 하위 클래스의 displayStudent() 메서드를 모두 호출할 수 있는 것을 확인할 수 있습니다.
예제 2
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 sup = new Test();
//Converting super class variable to sub class type
Test obj = (Test) sup;
obj.superMethod();
obj.subMethod();
}
}
출력 결과
Constructor of the super class Constructor of the sub class Method of the super class Method of the sub class
이 예제에서도 마찬가지로, 하위 클래스 Test의 객체를 상위 클래스 타입 참조 변수 sup에 담은 후 캐스트 연산자를 통해 Test 타입으로 변환하고 있습니다. 그 결과 상위 클래스의 메서드와 하위 클래스의 메서드를 모두 정상적으로 호출할 수 있습니다.
참고: 실제 객체가 해당 하위 클래스의 인스턴스가 아닌 경우 캐스트를 시도하면 ClassCastException이 발생하므로, 필요에 따라 instanceof 연산자를 사용해 변환 가능 여부를 미리 확인하는 것이 안전합니다.