ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Book_368_7_21
    자바의 정석 문제풀이 2021. 8. 19. 17:47

    다형성

     

    class Product{

    int price;

    int bonusPoint;

     

    public Product(int price) {

    this.price=price;

    bonusPoint=(int)(price/10.0);  //보너스점수는 제품가격의 10%

    }

    }

     

     

    class Tv extends Product{

    Tv(){

    //부모클래스의 생성자 product(int price)를 호출

    super(100);  //tv의 가격

    }

    //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+"을/를 구입하셨습니다");

    }

    }

     

    public class Book_368_7_21 {

     

    public static void main(String[] args) {

     

    Buyer b=new Buyer();

     

    b.buy(new Tv());  //티비 구입

    b.buy(new Computer());  //컴퓨터 구입

     

    System.out.println("현재 남은 돈: "+b.money+"만원");

    System.out.println("현재 보너스점수: "+b.bonusPoint+"점");

    }

    }

     

    //결과

    Tv을/를 구입하셨습니다

    Computer을/를 구입하셨습니다

    현재 남은 돈: 700만원

    현재 보너스점수: 30점

    '자바의 정석 문제풀이' 카테고리의 다른 글

    Book_364_7_18  (0) 2021.08.19
    Book_366_7_20  (0) 2021.08.19
    Book_227_5_23  (0) 2021.08.10
    Book_218_5_19(2차원배열+과목별 점수)  (0) 2021.08.10
    Book_197_5_06(배열의 최대값,최소값)  (0) 2021.08.09

    댓글

Designed by Tistory.