publicclassSuper{ public name = "父类"; publicvoidMyName(){ System.out.println("名字:"+name); } }
publicclassSubextendsSuper{ public name = "子类"; publicvoidMyName(){ System.out.println("名字:"+name); } } public Class Test{ publicstaticvoidmain(String args[]){ Super super = new Sub();//向上转型 Sub sub = (Sub)super;//向下转型,且super指向子类对象 //注属性不会覆写,super是父类型引用所以指向的属性是父类型属性 super.MyName();//输出:名字:父类 sub.MyName();//输出:名字:子类
//super_1指向的是父类型,强制转换的时候出错 Super super_1 = new Super(); Sub sub_1 = (Sub)super_1;//编译错误,ClassCaseException