Jam's story
다형성 예제+ Vector 본문
package days22;
import java.util.Vector;
/**
* @author 지민
* @date 2022. 3. 20. - 오후 3:31:17
* @subject
* @content
*
*/
public class Ex01 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Buyer b=new Buyer();
b.buy(new Tv());
Computer com=new Computer();
b.buy(com);
b.buy(new Audio());
b.summary();
b.refund(com);
}}
class Product{
int price;
int bonusPoint;
Product(int price){
this.price=price;
bonusPoint=(int)(price/10.0);
}
}
class Tv extends Product{
Tv(){
super(200);
}
@Override
public String toString() {
return "Tv";
}
}
class Computer extends Product{
Computer(){
super(300);
}
@Override
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;
Vector item=new Vector();
int i=0;
void buy(Product p){
if(money<p.price){
System.out.println("잔액이 부족함");
return;
}
item.add(p);
money-=p.price;
bonusPoint+=p.bonusPoint;
System.out.println(p+"를 구입하셨습니다.");
}
void refund(Product p) {
if(item.remove(p)) {
money+=p.price;
bonusPoint-=p.bonusPoint;
System.out.println(p+"를 반품했어요 ");
}
}
void summary() {
int sum=0;
StringBuffer itemList=new StringBuffer();
if(item.isEmpty()) {
System.out.println("구입한게 없어");
return;
}
for(int i=0; i<item.size(); i++) {
Product p=(Product)item.get(i);
sum+=p.price;
itemList .append((i==0) ? " "+p : ","+p);
}
System.out.println("구입한 물품 총 가격:"+sum);
System.out.println("구입하신 제품은 "+itemList);
}
}
'자바' 카테고리의 다른 글
[에러] The field MyPoint.x is not visible (0) | 2022.03.11 |
---|---|
[오류]No enclosing instance of type --- is accessible. Must qualify the allocation with an enclosing instance of type (0) | 2022.03.11 |
예외처리 (0) | 2022.02.02 |
자바 구구단 3행 3열로 입력받아 출력 중복은 제외 (0) | 2022.01.31 |
중첩 클래스 와 중첩 인터페이스 (0) | 2022.01.27 |