迷惑了?java书看不下了,大家帮我看看这问题
public class SuperClass {
public void method(){
System.out.println( "SuperClass.method() ");
}
public void method(SuperClass superObj,SuperClass subObj){
System.out.println( "SuperClass.method(SuperClass,SuperClass) ");
}
}
public class SubClass extends SuperClass{
public void method(){
System.out.println( "SubClass.method() ");
}
public void method(SuperClass superObj,SubClass subObj){
System.out.println( "SubClass.method(SuperClass,SubClass) ");
}
public void method(SubClass superObj,SuperClass subObj){
System.out.println( "SubClass.method(SubClass,SuperClass) ");
}
public void method(SubClass superObj,SubClass subObj){
System.out.println( "SubClass.method(SubClass,SubClass) ");
}
}
public class OverloadDemo {
public static void main(String[] args) {
SuperClass superObj=new SuperClass();
SubClass subObj=new SubClass();
SuperClass superReferToSub=subObj;
System.out.println();
subObj.method(superObj, superObj);
subObj.method(subObj, subObj);
subObj.method(superReferToSub, superReferToSub);
System.out.println();
superReferToSub.method();
superReferToSub.method(superObj, superObj);
superReferToSub.method(subObj, subObj);
superReferToSub.method(superReferToSub, superReferToSub);
}
}
执行结果是:
SuperClass.method(SuperClass,SuperClass)
SubClass.method(SubClass,SubClass)
SuperClass.method(SuperClass,SuperClass)//1
SubClass.method()//2
SuperClass.method(SuperClass,SuperClass)
SuperClass.method(SuperClass,SuperClass)
SuperClass.method(SuperClass,SuperClass)
问
1.既然subObj.method(superReferToSub, superReferToSub)没有调用SubClass.method(SubClass,SubClass),也就是说明SuperClass superReferToSub=subObj;的superReferToSub还是超类,但是为什么下面的
2.既然superReferToSub是超类,那么应该调用超类的method函数
SuperClass superRef=superObj;
superRef=subObj;superRef还是SuperClass 类? 我都快崩溃了,谁知道啊~~
------解决方案--------------------不要抑闷,语言是不会有问题的.
你子类里的方法除了第一个方法method(){}覆盖了父类的方法外,其它都只是重写了父类的方法,
相当于在父类的基础上添加了三个新的方法,跟父类method(SuperCalss s, SuperClass s)是平起平座的,superRef=subObj;superRef是SubClass类了,不过因为父类的方法没有被覆盖,那么这种现象肯定是正常的了
------解决方案--------------------