Java中的继承简单说明 [英] Inheritance in Java simple clarification
问题描述
所以,我有这个:
public class A {
public int a = 0;
public void m(){
System.out.println("A"+a);
}
}
这:
public class B extends A {
public int a = 5 ;
public void m (){
System.out.println("B"+a);
}
public static void main(String[] args) {
A oa = new A();
B ob = new B();
A oab = ob;
oa.m();
ob.m();
oab.m();
System.out.println("AA"+oa.a);
System.out.println("BB"+ob.a);
System.out.println("AB"+oab.a);
}
}
输出:
A0
B5
B5
AA0
BB5
AB0
我不明白为什么 oab.m(); 输出是 B5 而不是 A0 .谁可以给我解释一下这个?
I don't understand why oab.m(); output is B5 instead of A0. Can someone explain this to me?
推荐答案
这就是多态的全部要点. oab
的具体类型为B
(因为使用new B()
创建了对象).因此调用了B.m()
方法.
That's the whole point of polymorphism. The concrete type of oab
is B
(since the object was created with new B()
). So the method B.m()
is called.
在 http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29中查看动物示例了解其用途.如果您有一只动物,而这只动物是一只猫,您会期望它说喵!"当你说话时.
Look at the Animal example in http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29 to understand why it's useful. When you have an animal, and this animal is a Cat, you expect it to say "Meow!" when you make it talk.
这篇关于Java中的继承简单说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!