public class PolyTest
{
public static void main(String[] args)
{
//向上类型转换
Dog dog = new Dog();
Animal animal = dog;
animal.run();
//向下类型转换
Animal a = new Dog();
Dog d = (Dog)a;
d.run();
}
}
class Animal
{
public void run()
{
System.out.println("animal is run");
}
}
class Dog extends Animal
{
public void run()
{
System.out.println("dog is run");
}
}
作者: 庄星睿 时间: 2012-9-6 11:12
楼主写错了吧
Sub2 sub = new Sub2();
Sup sup = new Sup();
sub = (Sub2) sup; //这样写相当于 sub =(Sub2)(new Sup());了
sub.method();
sub是子类型,而sup是父类型的,只有在多态中才可以,Sup s = new Sub2();
Sub2 s2=(Sub2)s;
即 Animal a = new Cat();
Cat c=(Cat)a;
楼主的写法相当于这样了:是不能把动物强转成猫的
Animal a = new Animal();
Cat c = new Cat();
c=(Cat)a;
public class OverrideTest1 {
public static void main(String[] args) {
Sub2 sub = new Sub2();
Sup sup = new Sup();
sub = (Sub2) sup;/* 我写的向下转型的例子 运行的时候报错,这么向下转型不行的吗?不可以,向下转型的时必须在初始化阶段,就声明向下转换的父类,格式如下:
子类 子类对象=(子类)父类对象*/
sub.method();
}
}
class Sup{
public void method(){
System.out.println("father");
}
}
class Sub2 extends Sup{
public void method() {
System.out.println("children");
}
}
对于向上类型的,程序会自动完成,对于向下类型的转换,必须声明指出要转型的子类类型 作者: 王陶成 时间: 2012-9-6 12:59
要上下转型,就要先向上转型,否则会报类型转换异常ClassCastException,
public static void main(String[] args) {
Sup sup = new Sub2();//你要添加一个向上转型
Sub2 sub = new Sub2();
sub = (Sub2)sup;
sub.method();
}