Parameter polymorphism
부모 클래스 매개변수에 자식 클래스도 들어갈 수 있다!
참조형 매개변수는 메소드 호출시, 자신과 같은 타입 또는 자손 타입의 인스턴스를 넘겨줄 수 있다.
Pros and Cons of parameter polymorphism
Pros
다형적 parameter : 참조형 매개변수는 메소드 호출시, 자신과 같은 타입 또는 자손 타입의 인스턴스를 넘겨줄 수 있다.
Multiple object using one array
다형성이란
조상 객체 참조변수로 자손 객체 다룰 수 있다.
Tv t = new SmartTv();2. 참조 변수 형변환 - 리모콘 바꾸기(control the number of usable members;사용가능한 멤버 갯수 조절)
3. instanceof operator : check casting(형변환 가능여부 확인할 때 쓰인다.)
*오버로딩 : 메소드 이름 같고, 매개변수 타입 다른 것.
아래의 코드는 많은 오버로딩으로 인해 코드의 유지보수가 어려워지고 코드가 중복되는 단점이 있다.
class Product {
int price;
int bonusPoint;
}
class Tv extends Product {}
class Computer extends Product {}
class Audio extends Product {}
class Buyer {
int money = 1000;
int bonusPoint = 0;
void buy(Product p) {
money -= p.price;
bonusPoint += p.bonusPoint;
}
}
void buy(Tv t) {
money -= t.price;
bonusPoint += t.bonusPoint;
}
void buy(Computer c) {
money -= c.price;
bonusPoint += c.bonusPoint;
}
void buy(Audio a) {
money -= a.price;
bonusPoint += a.bonusPoint;
}개선된 코드 :
Last updated
Was this helpful?