继承
class Value {
    private int count = 1;
    private Value(int count) {
        this.count = count;
    }
    public static final Value
            v1 = new Value(1),
            v2 = new Value(2),
            v3 = new Value(3);
}
class Person {
    public void eat(Value v) {
        System.out.println("Person.eat()");
    }
}
class Teacher extends Person {
    public void eat(Value v) {
        System.out.println("Teacher.eat()");
    }
}
class Student extends Person {
    public void eat(Value v) {
        System.out.println("Student.eat()");
    }
}
public class UpcastingDemo {
    public static void show(Student s) {
        s.eat(Value.v1);
    }
    public static void show(Teacher t) {
        t.eat(Value.v1);
    }
    public static void show(Person p) {
        p.eat(Value.v1);
    }
    public static void main(String[] args) {
        Student s = new Student();
        Teacher t = new Teacher();
        Person p = new Person();
        show(s);
        show(t);
        show(p);
    }
}
这种做法一个很明显的缺陷就是必须为每一个Person类的衍生类定义与之紧密相关的方法,产生了很多重复的代码。另一方面,对于如果忘记了方法的重载也不会报错。上例中的三个show方法完全可以合并为一个:
 
                    
                     
                    
                 
                    
                

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号