polymorphism (다형성) Example 본문

Programming/Java

polymorphism (다형성) Example

쩡호 2018. 1. 19. 10:02
package javafuture;


import javafx.scene.Parent;

public class Example {
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);
}
}

class Product{
int price; // product's price
int bonusPoint; // membership point when you buy something

Product(int price){
this.price=price;
this.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 Buyer{
int money=1000;
int bonusPoint=0;

void buy(Product p){
if(money<p.price){
System.out.println("No Money");
return;
}

money-=p.price;
bonusPoint+=p.bonusPoint;
System.out.println("You bought "+p);
}
}


'Programming > Java' 카테고리의 다른 글

다형성 예제3 (Vector 추가)  (0) 2018.01.19
다형성 예제 2 (객체 배열 추가)  (0) 2018.01.19
피보나치  (1) 2018.01.17
단축키  (0) 2018.01.13
Java의 정석 공부  (0) 2018.01.13
Comments