public class Dog {
private String type;
private int age;
// object class (최상위) override
public String toString(){
return "Dog class";
}
}
class PetDog extends Dog {
private String owner;
private String FoodType;
public String toString(){
return "PetDog class";
}
}
class PoliceDog extends PetDog{
private String PolicID;
public String toString(){
return "PoliceDog class";
}
}
class Testing {
public static void main(String[] args){
Dog dog1 = new Dog();
Dog dog2, dog3, dog4;
// general class에서 instance -> polymorphism
dog2 = new PoliceDog();
dog3 = new PetDog();
dog4 = dog3;
System.out.println(dog2.toString());
// PoliceDog class
}
}
2. Downcasting
dog3 = new Dog():
자식 클래스의 인스턴스가 부모 클래스로 다시 참조하는 것
권장되지 않음
public class Parent()
public class Child extends Parent(){
public static void main(String args[]) {
Parent parent = new Child();
Child child = (Child) Parent();
// valid downcasting
}
}
...
PoliceDog dog5;
dog5 = new Dog();
// downcasting -> error
dog5 = (PoliceDog) new Dog();
// runtime error
Dog dog5 = new PoliceDog();
PoliceDog dog6 = (PoliceDog) dog5;
// no error dog5는 Dog 객체이지만 PoliceDog를 참조하고 있기 때문에 downcasting 가능
3. Polymorphism using Abstract Classes
public abstract class Employee{}
public abstract void draw();
abstract superclass : 실제 객체를 만들기에 너무 general 한 것, subclass 간 공통적인 것만을 명시함