상속관계의 클래스가 늘어나면 오버로딩이 필요한 메소드가 많아진다.
여기에서 ✨✨공통의 조상 타입을 매개변수로 받는 메소드 하나✨✨를 작성하고 다형성을 사용하면, 자손을 받는 메소드 여럿을 따로 작성하지 않아도(오버로딩 하지 않아도) 자유로이 자손들을 대입할 수 있다.(여러 타입의 객체를 받을 수 있다.
✨✨ 참조형 매개변수는 메소드 호출 시, 자신과 같은 타입 또는 자손타입의 인스턴스를 매개변수로 넘길 수 있다.
class Product {
int price;
int bonusPoint;
Product(int price){ //생성자
this.price = price;
bonusPoint = (int)(price/10.0);
}
}
class Tv1 extends Product {
Tv1(){ //생성자
super(1100); //조상클의 생성자를 super사용해 호출하고 this.~ 초기화
}
//Object클의 toString() 오버라이딩, public은 원래 있던 거
public String toString() {
return "Tv";
}
}
class Computer extends Product {
Computer(){
super(300);
}
public String toString() {
return "Computer";
}
}
class Buyer {
int money = 1000;
int bonusPoint = 0;
//(Tv1 t)...를 반복하는 것보다 조상인 (Product p)로
void buy(Product p) {
if(money < p.price) {
System.out.println("잔액이 부족합니다.");
return;
}
money -= p.price;
bonusPoint += p.bonusPoint;
System.out.println(p+"을/를 구입하셨습니다.");
//p.toString()
}
}
public class Ex7_08 {
public static void main(String[] args) {
Buyer b = new Buyer();
// Product p = new Tv1();
// b.buy(p);
//p를 따로 만들어서 집어넣거나(p를 따로 사용할 데가 있는 경우 만들고)
//아래처럼 바로 넣을 수 있다.
b.buy(new Tv1()); //buy메소드 호출
b.buy(new Computer());
//각 매개변수는 참조변수, 즉 주소값
//new ~를 통해 객체 생성함?
System.out.println("현재 남은 돈은 "+b.money+"입니다.");
System.out.println("현재 보너스점수는 "+b.bonusPoint+"입니다.");
}
}
잔액이 부족합니다.
Computer을/를 구입하셨습니다.
현재 남은 돈은 700입니다.
현재 보너스점수는 30입니다.
와 너무 복잡하다. 다시 공부!!
-> 업그레이드!!
Ch07Re2
Ex7_08
class Product{
int price;
int bonusPoint;
public Product(int price) { //매개생성자
super(); //생성자 첫줄에 생성자 호출이 없으므로 자동으로
this.price = price;
bonusPoint = (int) (price/10.0);
}
}
class Tvv extends Product{
public Tvv(int price) { //매개생성자
super(price); //생성자 첫줄에 생성자 호출이 있음(없으면 super() 자동으로)
}
public String toString() { return "Tv";}
}
class Computer extends Product{
public Computer(int price) { //매개생성자
super(price);
}
public String toString() { return "Computer";}
}
class Buyer{
int money;
int bonusPoint;
public Buyer(int money) { //매개생성자
super(); //생성자 첫줄에 생성자 호출이 없으므로 자동으로
this.money = money;
bonusPoint = 0;
System.out.println("현재 소지금액은 "+money+"원입니다.");
System.out.println("현재 보너스점수는 "+bonusPoint+"점입니다.");
}
void buy(Product p) {
if(money<p.price) {
System.out.println("금액이 부족하여 "+p+"을/를 구입하실 수 없습니다.");
//******return; 으로 안끝내면 다음 문장들이 실행됨!!!
return;
}
money -= p.price;
bonusPoint += p.bonusPoint;
System.out.println(p+"을/를 구입하셨습니다.");
}
}
public class Ex7_08 {
public static void main(String[] args) {
Buyer b = new Buyer(1000);
b.buy(new Tvv(500));
b.buy(new Computer(3000));
System.out.println("잔액은 "+b.money+"원입니다.");
System.out.println("보너스점수는 "+b.bonusPoint+"점입니다.");
}
}
현재 소지금액은 1000원입니다.
현재 보너스점수는 0점입니다.
Tv을/를 구입하셨습니다.
금액이 부족하여 Computer을/를 구입하실 수 없습니다.
잔액은 500원입니다.
보너스점수는 50점입니다.