TIL/남궁성의 자바의 정석
자바의 정석 ch7-27,28 매개변수 다형성
minOE
2023. 12. 25. 22:16
728x90
ch7-27 매개변수의 다형성
다형성 잠시 복습 ..
1)
Tv t = new SmartTv(); // 조상 참조변수 t로 자손 객체를 가르킬 수 있다.
2) 참조변수의 형변환 <- 사용 가능한 멤버개수 조절
3) instaceof 연산자 형변환 가능 여부 확인
매개변수 다형성을 쓰지 않았을 때class Product{ int price; //제품가격 int bonusPoint; //보너스 점수 Product(int price){ this.price = price; bonusPoint = (int) (price/10.0); } } class Tv extends Product { Tv() { super(100); } } class Computer extends Product{ Computer() { super(200); } } class Audio extends Product{ Audio(){ super(50); } } class Buyer{ // 물건 사는 사람 int money =1000; //소유 금액 int bonusPoint =0; //보너스 점수 void buy(Tv t){ money -= t.price; bonusPoint += t.bonusPoint; System.out.println("Tv를 구입하셨습니다"); } void buy(Computer c){ money -= c.price; bonusPoint += c.bonusPoint; System.out.println("Computer를 구입하셨습니다"); } void buy(Audio a){ money -= a.price; bonusPoint += a.bonusPoint; System.out.println("Audio를 구입하셨습니다"); } } public class Main { public static void main(String[] args) { Buyer buyer = new Buyer(); buyer.buy(new Tv()); buyer.buy(new Computer()); buyer.buy(new Audio()); System.out.println("남은 돈은"+ buyer.money+"입니다"); System.out.println("현재 보너스 점수는" +buyer.bonusPoint+"입니다"); } }
출력
ch7-28 매개변수의 다형성 실습
package ch7_28; class Product{ int price; //제품가격 int bonusPoint; //보너스 점수 Product(int price){ this.price = price; bonusPoint = (int)(price/10.0); } } class Tv extends Product { Tv() { super(100); } public String toString() { return "Tv"; } } class Computer extends Product { Computer() { super(200); } public String toString() { return "Computer";} } class Audio extends Product { Audio(){ super(50); } public String toString() { return "Audio";} } class Buyer { // 물건 사는 사람 int money = 1000; //소유 금액 int bonusPoint = 0; //보너스 점수 void buy(Product p) { if (money < p.price) { System.out.println("잔액이 부족합니다"); } money -= p.price; bonusPoint += p.bonusPoint; System.out.println(p + "을/를 구입하셨습니다"); } } public class Main { public static void main(String[] args) { Buyer buyer = new Buyer(); buyer.buy(new Tv()); buyer.buy(new Computer()); buyer.buy(new Audio()); System.out.println("남은 돈은 " + buyer.money + "입니다"); System.out.println("현재 보너스 점수는 " + buyer.bonusPoint + "입니다"); } }
출력class Buyer의 메서드를 하나만 만들면 된다. Product 자손의 개수가 많을수록 매개변수 다형성을 이용한 프로그래밍의 장점이 더 빛을 바랄 것 같다.
매개변수 다형성을 이용하면 한 메서드로 여러 타입의 객체를 처리할 수 있으므로 코드의 유연성과 재사용성이 향상된다. 특히, Product 클래스를 상속받은 여러 자손 클래스가 있을 때, 이들을 동일한 메서드로 다루는 것은 매우 효과적일 것이다.
728x90

