请问一个JAVA多态问题! [关键字: 多态实现问题]
请问一个JAVA多态问题!
class SupclassTest{
int i=11;
SupclassTest(){
System.out.println("Supclass Loading....");
}
int getNum(){
return i;}
}
class Subclass extends SupclassTest
{
int i=12;
Subclass(){
System.out.println("Subclass Loading.....");
System.out.println("the method of super is "+" " +super.getNum());
}
int getNum(){
return i+12;
}
public static void main(String[] args){
Subclass sb=new Subclass();
SupclassTest sp=sb;{
System.out.println("the i of sp is "+" " +sp.i);
System.out.println("the i of sb is "+" " +sb.i);
System.out.println("the method of sp is "+" " +sp.getNum());
System.out.println("the method of sb is "+" " +sb.getNum());}
}
}
我想问一下,用子类的实例赋值给声明为父类的变量,为什么在打印时,sp.i返回的是父类中i的值11,但是在用sp.getNum()方法时,返回却是子类的getNum()方法的值24,
sp不是指向一个sb的对象吗,为什么在覆盖时,变量和方法的返回的引用结果不一样,这个多态是怎么理解,能详细解释一下内在里面的运行结构和布局,还有具体的告诉我
到底怎么运行的这个程序,谢谢!!!
请问一个JAVA多态问题!
class SupclassTest{
int i=11;
SupclassTest(){
System.out.println("Supclass Loading....");
}
int getNum(){
return i;}
}
class Subclass extends SupclassTest
{
int i=12;
Subclass(){
System.out.println("Subclass Loading.....");
System.out.println("the method of super is "+" " +super.getNum());
}
int getNum(){
return i+12;
}
public static void main(String[] args){
Subclass sb=new Subclass();
SupclassTest sp=sb;{
System.out.println("the i of sp is "+" " +sp.i);
System.out.println("the i of sb is "+" " +sb.i);
System.out.println("the method of sp is "+" " +sp.getNum());
System.out.println("the method of sb is "+" " +sb.getNum());}
}
}
我想问一下,用子类的实例赋值给声明为父类的变量,为什么在打印时,sp.i返回的是父类中i的值11,但是在用sp.getNum()方法时,返回却是子类的getNum()方法的值24,
sp不是指向一个sb的对象吗,为什么在覆盖时,变量和方法的返回的引用结果不一样,这个多态是怎么理解,能详细解释一下内在里面的运行结构和布局,还有具体的告诉我
到底怎么运行的这个程序,谢谢!!!
猴子 B = A这时候等于告诉 告诉观众笼子里面是个猴子
OK 这时候你问观众 B的毛上面颜色,观众会根据常识回答你 棕色 (猴子的毛当然是棕的)
你又说了,那大家拔根毛出来仔细看看吧(残忍了)
结果拔出来一根 发现是 金色 的。A是 金丝猴 的事实是不容忽视的哦~ 从金丝猴身上拔的毛当然是金色的咯呃,扯远了~见笑
sb.i指向了不同的i,而sp.getNum()与sb.getNum()调用的是同一个方法,所以一样