在java多态性中这样一句话: 实际调用的方法版本取决于对象的类型而不是引用变量的类型。
部分引用来自百度知道和 chenssy
此话什么意思?能否举个简单例子
<pre name="code" class="java">public class Polymorphism {
public static void main(String[] args) {
//既然是多态,java 中重载和重写都是多态的体现,你问的这句话肯定不属于重载则用重写来解释
// 这里声明了一把枪,变量为gun,但他却指向了一把Ak47对象,也就是说 gun虽然是Gun的引用,但实际是一个Ak47对象
//那么gun.shot其实调用的是Ak47.shot 而不是Gun自己的shot
Gun gun = new Ak47();
gun.shot();
}
}
class Gun {
public void shot() {
System.out.println("突!");
}
}
class Ak47 extends Gun {
public void shot() {
System.out.println("突!突!突!突!突!");
}
}
多态机制遵循的原则概括为:当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法,但是它仍然要根据继承链中方法调用的优先级来确认方法,该优先级为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。
经典实例。
public class A {
public String show(D obj) {
return ("A and D");
}
public String show(A obj) {
return ("A and A");
}
}
public class B extends A{
public String show(B obj){
return ("B and B");
}
public String show(A obj){
return ("B and A");
}
}
public class C extends B{
}
public class D extends B{
}
public class Test {
public static void main(String[] args) {
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
System.out.println("1--" + a1.show(b));
System.out.println("2--" + a1.show(c));
System.out.println("3--" + a1.show(d));
System.out.println("4--" + a2.show(b));
System.out.println("5--" + a2.show(c));
System.out.println("6--" + a2.show(d));
System.out.println("7--" + b.show(b));
System.out.println("8--" + b.show(c));
System.out.println("9--" + b.show(d));
}
}
运行结果:
1--A and A
2--A and A
3--A and D
4--B and A
5--B and A
6--A and D
7--B and B
8--B and B
9--A and D
部分引用来自百度知道和 chenssy