ch7-27 매개변수의 다형성
- 참조형 매개변수는 메서드 호출시, 자신과 같은 타입 또는 자손타입의 인스턴스를 넘겨줄 수 있다.
장점
- 다형적 매개변수
- 하나의 배열로 여러종류 객체 다루기
다형성
- Tv t = new SmartTv(); - 조상타입의 참조변수로 자손 객체를 다루는 것
- 참조변수의 형변환 - 리모콘 바꾸기 (사용가능한 멤버 개수 조절)
- instanceof 연산자 - 형변환 가능여부 체크
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; // 보너스점수
}
// 추가 - 이렇게 하면 Tv타입만 가능하므로 메서드 오버로딩해서 가능
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;
}
/* 변경 */
// 조상타입을 매개변수로 해서 다형성을 이용해 모두 가능
void buy(Product p) {
money -= p.price;
bonusPoint += p.bonusPoint;
}
// 다형성
// 조상 = 자손
Product p1 = new Tv();
Product p2 = new Computer();
Product p3 = new Audio();
Buyer b = new Buyer();
Tv tv = new Tv();
Computer com = new Computer();
b.buy(tv);
b.buy(com);
→ 다형적 매개변수의 장점
class Product {
int price; // 제품가격
int bonusPoint; // 제품구매 시 제공하는 보너스점수
Product(int price) {
this.price = price;
bonusPoint = (int)(price/10.0); // 보너스점수는 제품가격의 10%
}
}
class Tv1 extends Product{
Tv1() {
// 조상 클래스의 생성자 Product(int price)를 호출한다.
super(100); // Tv의 가격을 100만원으로 한다.
}
//Object 클래스의 toString()을 오버라이딩한다.
public String toString() { return "Tv";}
}
class Computer extends Product {
Computer() { super(200); }
public String toString() { return "Computer"; }
}
class Buyer {
int money = 1000;
int bonusPoint = 0;
void buy(Product p) {
if(money < p.price) {
System.out.println("잔액이 부족하여 물건을 살 수 없습니다.");
return;
}
money -= p.price;
bonusPoint += p.bonusPoint;
// System.out.println( p.toString() + "을/를 구입하셨습니다."); 자동으로 toString됨
System.out.println( p + "을/를 구입하셨습니다.");
}
}
class Ex7_8 {
public static void main(String arg[]) {
Buyer b = new Buyer();
b.buy(new Tv1());
b.buy(new Computer());
System.out.println("현재 남은 돈은" + b.money + "만원입니다.");
System.out.println("현재 보너스 점수는" + b.bonusPoint + "점입니다.");
}
'Dev > Java' 카테고리의 다른 글
Server Add and Remove에 프로젝트가 안 뜰때 (0) | 2022.07.12 |
---|---|
[Java] 자바의 정석 기초편 ch7-26 instanceof 연산자 (0) | 2022.06.27 |
[Java] 자바의 정석 기초편 ch7-24,25 참조변수의 형변환 (0) | 2022.06.22 |
[Java] 자바의 정석 기초편 ch7-23 다형성(polymorphism) (0) | 2022.06.22 |
[Java] 자바의 정석 기초편 ch7-22 캡슐화와 접근 제어자 (0) | 2022.06.22 |