多态:父类的引用指向子类的实例,调用父类的方法表现为子类的形为。
你只能调用父类的方法,父类里没有声明的方法,是不能调用的。
其原理是:
在编译阶段,z的类型是A,在运行阶段,z的类型才是C,也就是说z的表现类型是A,实际类型是C。因为A里没有方法c1,所以调用z.c1(),编译不过,编译器认为A里没有方法c1。

解决方案 »

  1.   


    11. abstract class Vehicle { public int speed() { return 0; }
    12. class Car extends Vehicle { public int speed() { return 60; }
    13. class RaceCar extends Car { public int speed() { return 150; } ...
    21. RaceCar racer = new RaceCar();
    22. Car car = new RaceCar();
    23. Vehicle vehicle = new RaceCar();
    24. System.out.println(racer.speed() + ", " + car.speed()
    25. + ", " + vehicle.speed());
    What is the result?
    A. 0, 0, 0
    B. 150, 60, 0
    C. Compilation fails.
    D. 150, 150, 150
    E. An exception is thrown at runtime.
    这道题答案是D,为什么car调用的是RaceCar里面的speed呢
      

  2.   

    RaceCar racer = new RaceCar();
    Car car = new RaceCar();
    Vehicle vehicle = new RaceCar();父类引用指向子类对象,指向的是同一个构造方法new出来的对象的引用,自然调用的是同一个对象的方法
      

  3.   

    学习了! A z = new C(); 调用抽象父类的实例,必须父类的方法必须存在,即必须声明该方法,c1()这个方法在抽象父类中不存在,所以是不能使用的,如果想使用只能是 c z=new c(); z.c1();
      

  4.   


    11. abstract class Vehicle { public int speed() { return 0; }
    12. class Car extends Vehicle { public int speed() { return 60; }
    13. class RaceCar extends Car { public int speed() { return 150; } ...
    21. RaceCar racer = new RaceCar();
    22. Car car = new RaceCar();
    23. Vehicle vehicle = new RaceCar();
    24. System.out.println(racer.speed() + ", " + car.speed()
    25. + ", " + vehicle.speed());
    What is the result?
    A. 0, 0, 0
    B. 150, 60, 0
    C. Compilation fails.
    D. 150, 150, 150
    E. An exception is thrown at runtime.
    这道题答案是D,为什么car调用的是RaceCar里面的speed呢伙计,你看到这个没有Car car = new RaceCar(); ???父类引用子类的实例, Vehicle Car  RaceCar 他们的数据类型相同,是继承与被继承的关系,当 父类  实例 =new 子类构造方法时,调用父类的方法,也可以调用子类的方法,当然如果是抽象类和接口另说了.
      

  5.   


    11. abstract class Vehicle { public int speed() { return 0; }
    12. class Car extends Vehicle { public int speed() { return 60; }
    13. class RaceCar extends Car { public int speed() { return 150; } ...
    21. RaceCar racer = new RaceCar();
    22. Car car = new RaceCar();
    23. Vehicle vehicle = new RaceCar();
    24. System.out.println(racer.speed() + ", " + car.speed()
    25. + ", " + vehicle.speed());
    What is the result?
    A. 0, 0, 0
    B. 150, 60, 0
    C. Compilation fails.
    D. 150, 150, 150
    E. An exception is thrown at runtime.
    这道题答案是D,为什么car调用的是RaceCar里面的speed呢
    父类引用指向子类实例,调用父类方法,表现为子类的形为。
    这三个引用,引的都是RaceCar实例,三个speed调用,都执行的是RaceCar类里的speed方法。