ex) 아이가 장난감을 가지고 노는 경우
public class Kids{
private Toy toy;
public void setToy(Toy toy){
this.toy = toy;
}
public void play() {
System.out.println(toy.toString());
}
}
public class Robot extends Toy{
public String toString(){
return "Robot";
}
}
public class Main{
public static void main(String[] args) {
Toy t = new Robot();
Kid k = new Kid();
k.setToy(t);
k.play();
}
}
public class Lego extends Toy{
public String toString(){
return "Lego";
}
}
public class Main{
public static void main(String[] args) {
Toy t = new Lego();
Kid k = new Kid();
k.setToy(t);
k.play();
}
}
Reference