多态:父类的引用指向子类的实例,调用父类的方法表现为子类的形为。
你只能调用父类的方法,父类里没有声明的方法,是不能调用的。
其原理是:
在编译阶段,z的类型是A,在运行阶段,z的类型才是C,也就是说z的表现类型是A,实际类型是C。因为A里没有方法c1,所以调用z.c1(),编译不过,编译器认为A里没有方法c1。
你只能调用父类的方法,父类里没有声明的方法,是不能调用的。
其原理是:
在编译阶段,z的类型是A,在运行阶段,z的类型才是C,也就是说z的表现类型是A,实际类型是C。因为A里没有方法c1,所以调用z.c1(),编译不过,编译器认为A里没有方法c1。
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 vehicle = new RaceCar();父类引用指向子类对象,指向的是同一个构造方法new出来的对象的引用,自然调用的是同一个对象的方法
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 子类构造方法时,调用父类的方法,也可以调用子类的方法,当然如果是抽象类和接口另说了.
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方法。