끄적끄적 코딩

다형성 polymorphism
하나의 객체가 많은 형(타입)을 가질 수 있는 성질
상속 관계에 있을 때 조상 클래스의 타입으로 자식 클래스 객체를 레퍼런스 할 수 있다.

SpiderMan onlyOne = new SpiderMan("피터파커", false); 
SpiderMan sman = onlyOne; 
Person person = onlyOne; 
Object obj = onlyOne;

* 객체는 모두 Object에 담을 수 있다
* 기본형은 각각의 클래스형태가 있다 Wrapper클래스라고 함


다형성의 활용

  1. 다른 타입의 객체를 다루는 배열
  2. 매개변수의 다형성
int a = 10; 
Integer aobj = a; // int ==> Integer : autoboxing 
int sum = a + aobj; // Integer ==> int : unboxing
int sum2 = a + aobj.intValue();

다형성과 참조형 객체의 형 변환 메모리에 있는 것과 사용할 수 있는 것의 차이
메모리에 있더라도 참조하는 변수의 타입에 따라 접근할 수 있는 내용이 제한됨

child에서 super로 -> 묵시적 형변환 Phone phone = new Phone(); Object obj = phone;
super에서 child로 -> 명시적 형변환 Phone phone = new SmartPhone(); SmartPhone sPhone = (SmartPhone)phone

instanceof 연산자 실제 메모리에 있는 객체가 특정 클래스 타입인지 boolean으로 리턴

Person person = new Person();

if(person instanceof SpiderMan) { 
  SpiderMan sman = (SpiderMan) person; 
}

참조 변수의 레벨에 따른 객체의 멤버 연결

class SuperClass { 
  String x = "super";

  public void method() { 
    System.out.println("super class method"); 
  } 
}

class SubClass extends SuperClass { 
  String x = "sub";
  
  @Override 
  public void method() { 
    System.out.println("sub class method"); 
  } 
}

public class MemberBindingTest { 
  public static void main(String[] args) { 
    SubClass subClass = new SubClass(); 
    System.out.println(subClass.x); // sub 
    subClass.method(); //sub

    SuperClass superClass = subClass; 
    System.out.println(superClass.x); // super 
    superClass.method(); //sub 
  } 
}

정적 바인딩 (static binding)
컴파일 단계에서 참조 변수의 타입에 따라 연결이 달라짐
상속 관계에서 객체의 멤버 변수가 중복될 때 또는 static method

동적 바인딩 (dynamic binding)
다형성을 이용해서 메서드 호출이 발생할 때 runtime에 메모리의 실제 객체의 타입으로 결정
상속 관계에서 객체의 instance method가 재정의 되었을 때 마지막에 재정의 된 자식 클래스의 메서드가 호출됨
- 최대한 메모리에 생성된 실제 객체의 최적화 된 메서드가 동작

                                            정적 바인딩             /            동적바인딩
(수행속도)                     상대적으로 빠름            /            상대적으로 느림
(메모리 공간 활용 효율) 상대적으로 높음           /           상대적으로 낮음
(객체지향적)                                         ""            /           다형성으로 효율적인 코드 재사용 가능

System.out.println(sman.toString());
System.out.println(sman);

 

검색 태그