父类和子类的转化

来源:互联网 发布:matlab矩阵运算 编辑:程序博客网 时间:2024/06/06 21:43

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...  

}

}

必须某个对象构造成为指向子类的对象,这样在操作父类强制转为子类是可以成功的,否则会出错抛出异常的



0 0