class Base {
}
class Sub extends Base{
}
public class BaseSubTest{
public static void main(String[] args) {
Base base = new Base();
Base base = new Base();
base.hello(); // hello Base...
System.out.println(base.str);// hello Base...
Sub sub = new Sub(); // hello Sub...
sub.hello(); // hello Sub...
System.out.println(sub.str);
Base bs = new Sub();
System.out.println(bs.getClass());//class tao.test.Sub
bs.hello(); // hello Sub...
System.out.println(bs.str); // hello Base...
Sub s = (Sub) bs;
s.hello(); // hello Sub...
System.out.println(s.str); // hello Sub...
}
}
必须某个对象构造成为指向子类的对象,这样在操作父类强制转为子类是可以成功的,否则会出错抛出异常的