今天写了一个程序,关于父类和子类的类型转换问题,代码如下:让我头疼的是,红色字体的三句代码,第一句将子类对象传给父类对象,传递的是子类对象在内存中的单元地址,这时在原基础上单元又多了两个属性值,但是奇怪的是,怎么父类的对象也跟着变成了子类类型呢?不应该是子类跟随父类的类型吗?public class 多态 {
public static void main(String[] args) {
SonCla son = new SonCla();

FatherCla father = son;//引用类型的自动转换 , 子类对象传给父类对象,传的是对象引用吗?father变成了子类类型
System.out.println(father.getClass()); System.out.println(son.getClass());//子类对象怎么没有转换成父类对象类型?
System.out.println(son.age+"******");
System.out.println(son.name+"*****");
System.out.println(father.name+">>>>>");
father.printFatherName();
son.printSonName();
father.one();
father.two();//虚方法调用
System.out.println("======================================");

SonCla son2 = (SonCla)father;//引用类型的强制转换
System.out.println(father.getClass()+"%%%%");//father确实变成了子类对象类型
System.out.println(son2.name);
System.out.println(son2.sex);
System.out.println(son2.age);
son2.one();
son2.two();
son2.three();

System.out.println(son == father);//这三句输出true,表明它们引用同一个内存地址单元(已调试验证正确)
System.out.println(son == son2);
System.out.println(son2==father);
}
}
class FatherCla{
/* String name = "张三";
int age = 57;
*/
String name;
int age;
public void one(){
System.out.println("父类one方法");
}
public void two(){
System.out.println("父类two方法");
}
public void printFatherName(){
System.out.println(this.name);
}
}
class SonCla extends FatherCla{
String name = "张四";
char sex = '男';
public void three(){
System.out.println("子类three方法");
}
//方法覆盖
public void two(){
System.out.println("子类two方法");
}
public void printSonName(){
System.out.println(this.name);
}
}

解决方案 »

  1.   

    明确告诉你,传的是引用,father指向了子类定义的某些父类定义的接口,比如:
     class Father{
       public void one(){
        System.out.println("father");
      }
    }class child extends Father{
       public void one(){
        System.out.println("child!");
      }
    }
    代码中,father定义了接口协议:public void one()
    子类实现并重写该协议,也就是函数覆盖。执行FatherCla father = son,传递引用此时father指向child的内容,调用father.one(),肯定显示child的东西,这就是多态嘛,不然要多态干嘛?
    但是,father是father,son是son,类模版不一样,getClass()返回运行时类肯定不同
    再者FatherCla father = son是赋值,son并不会改变什么啊!只是把son的引用给了father