728x90
다형성
Animal > Person > Student
학생 객체 → 사람 관점 → 학생 관점 (O)
사람 객체 → 사람 관점 → 학생 관점 (X)
Person s2 = new Student(); // 조상 클래스의 타입(Person)으로 자식 클래스 객체(Student)를 참조
// s2.study(); // 오류남.. Person으로 보고 있음
Student st = new Person(); // 참조 불가능
상속 관계에 있을 때 조상 클래스의 타입으로 자식 클래스 객체를 참조할 수 있다.
활용
- 다른 타입의 객체를 다루는 배열
Person[] persons = new Person[3];
persons[0] = new Person();
persons[1] = new Student();
persons[2] = new Student();
다형성과 참조형 객체의 형 변환
- 메모리에 있는 것과 사용할 수 있는 것의 차이
Person p = new Student("박싸피", 20, "수학");
new Student
- Object - equals(), toString()
- Person - name, eat()
- Student - major, study()
Person p → p.study() 사용 불가
→ 메모리에 있더라도 참조하는 변수의 타입에 따라 접근할 수 있는 내용이 제한됨
Person p2 = new Person();
Student st2 = (Student) p2;
st2.study();
무늬만 Student인 Person → 메모리의 객체는 study() 없음
→ instanceof 연산자: 실제 메모리에 있는 객체가 특정 클래스의 타입인지 boolean으로 리턴
참조 변수의 레벨에 따른 객체의 멤버 연결
class Parent {
String x = "parent";
public void method() {
System.out.println("parent method");
}
}
class Child extends Parent {
String x = "child";
@Override
public void method() {
System.out.println("child method");
}
}
public class Test {
public static void main(String[] args) {
Child c = new Child();
System.out.println(c.x); // child
c.method(); // child method
Parent p = c;
System.out.println(p.x); // parent
p.method(); // child method
}
}
상속 관계에서 객체의 멤버 변수가 중복될 때
- 참조 변수의 타입에 따라 변수 bindng이 달라짐
상속 관계에서 객체의 메서드가 중복될 때 (메서드가 override되었을 때)
- 무조건 자식 클래스의 메서드가 호출됨 → virtual method invocation: 동적 바인딩
- 최대한 메모리에 생성된 실제 객체에 최적화된 메서드가 동작
728x90
'Java' 카테고리의 다른 글
[자바/Java] 객체 참조 시 인터페이스 사용 이유 (0) | 2022.07.28 |
---|---|
[자바/Java] 제네릭 Generics (0) | 2022.07.27 |
[자바/Java] 클래스(Class), 상속, 생성자(Constructor), 오버라이딩(Override) (0) | 2022.07.25 |
[자바/Java] 싱글톤(Singleton) 패턴, Static (0) | 2022.07.25 |
[자바/Java] 배열, 1차원 배열, 2차원 배열 정리 (0) | 2022.07.23 |