My footsteps
매개변수 다형성 본문
728x90
class Ex7_8 {
public static void main(String args[]) {
Buyer b = new Buyer(); //객체 b 생성
b.buy(new Tv1());
b.buy(new Computer()); //b가 가리키는 buy의 값에 tv1,computer객체 대입 → ★★매개변수의 다형성★★
System.out.println(b.money);
System.out.println(b.bonusPoint);
}
}
class Product {
int price;
int bonusPoint;
Product(int price) { //반환형식이 int형인 product매서드의 pirce 클래스
this.price = price; //iv와 lv구분(class의 price와 매서드의 price)위해 this사용. 두 price는 같은 값
bonusPoint = (int)(price/10.0); //그 price를 10.0으로 나누고 int형으로 반환한걸 bonuspoint에 대입한다
}
}
class Tv1 extends Product {
Tv1() { //매개변수가 없는 매서드
super(100); //부모인 product 클래스에 있는 매개변수에 100을 대입함. 즉, price에 100을 대입.
}
public String toString() { //매개변수가없는 반환형식이 string인 tostring 매서드
return "Tv"; //"tv"문자 자체를 반환한다
}
}
class Computer extends Product {
Computer() { //매개변수가 없는 매서드
super(200); //부모인 product 클래스에 있는 매개변수에 100을 대입함. 즉, price에 100을 대입. 이건 Tv1과 별개의 클래스라서
// 다른 값을 넣는것!
}
public String toString() {
return "Computer"; //"Computer"문자 자체를 반환한다
}
}
class Buyer {
int money = 1000;
int bonusPoint = 0;
void buy(Product p) { //p를 buy에 대입?
if(money < p.price) { //만약 갖고있는 money(=1000)보다 물건값(=p.price)이 비싸다면
System.out.println("잔액이 부족하여 물건 못삽니더");
return; //이 문구를 반환하고
}
money -= p.price; //가진 돈에서 구입한 제품의 가격을 빼고
bonusPoint += p.bonusPoint; //가진 포인트에서 보너스 점수를 추가한다
//tv는 100,computer는 200에 샀으니 둘이 더하면 300이라,갖고있는돈 1000-300=700
//tv보너스 점수는 10점, computer보너스 점수는 20점이라 둘이 더하면 30점.
//앞서 tv1과 computer에 각각 대입되었던 100,200이 여기에 순차적으로 들어와서 값이 반환된다
System.out.println(p.toString() + "을 구입하셨습니다"); //이 문구를 반환해라.
}
}
매개변수 다형성 결과값
Tv을 구입하셨습니다
Computer을 구입하셨습니다
700
30
728x90
'예습 > code' 카테고리의 다른 글
추상클래스 (0) | 2023.01.14 |
---|---|
여러 종류의 객체를 배열로 다루기 (0) | 2023.01.13 |
참조변수 형변환 (0) | 2023.01.13 |
접근제어자 (0) | 2023.01.13 |
참조변수 Super (0) | 2023.01.13 |