[조건]
- 각각의 클래스 생성
- 샌드위치 재료를 표시하는 메소드 정의
- 공통 부분은 오버라이딩
public static void main(String[] args){
Sandwich sandwiches = new Sandwich[3];
sandwiches[0] = new EggSandwich();
sandwiches[1] = new ChickenSandwich();
sandwiches[2] = new BeefSandwich();
for(Sandwich sandwich : sandwiches){
sandwich.cook();
System.out.println("-------------");
}
}
class EggSandwich{
public String name;
public EggSandwich(){
this("계란 샌드위치")
}
public EggSandwich(String name){
this.name = name;
}
public void cook(){
System.out.println(this.name + "의 재료는?");
System.out.println("식빵");
System.out.println("양상추");
System.out.println("피클");
System.out.println("계란");
}
}
class ChickenSandwich extends EggSandwich{
public ChickenSandwich(){
super("치킨 샌드위치")
}
@Overriding
public void cook(){
super.cook();
System.out.println("치킨");
}
}
class BeefSandwich extends EggSandwich{
public BeefSandwich(){
super("소고기 샌드위치")
}
@Overriding
public void cook(){
super.cook();
System.out.println("소고기");
}
}
[반성할 점]
- 오버라이딩 후 부모 클래스의 메소드를 가져올때 super.메소드 이름을 하여 가져올 수 있다.