您的位置:首页 > 编程语言 > Java开发

java_类型强转

2013-11-09 14:46 225 查看
class Father{
public void fromFather(){
System.out.println("fromFather");
}
}
interface interfaceSon{
public void fromInterSon();
}
class Son extends Father implements interfaceSon {
public void fromFather(){
System.out.println("fromFather2");
}
public void formSon(){
System.out.println("fromSon");
}
public void fromInterSon(){
System.out.println("formInterfaceOfSon");
}
}
class Test{
public void test1(Father f){
f.fromFather();
// the method is not the method of super,
//  which has be overwritten,but now can be used by super
//        f.fromSon();
//   0:    can not be compiled,need create method in Father
System.out.println("--------"+f.toString());
//   1:  com.h.Son@1bab50a
System.out.println("--------"+f.getClass());
//   1:  class com.h.Son
}
public void test2(Father f){
((Son)f).fromFather();
((Son)f).formSon();
((Son)f).fromInterSon();
System.out.println("--------"+f.toString());
//   2:  com.h.Son@1bab50a
System.out.println("--------"+f.getClass());
//   2:  class com.h.Son
}
public void test3(Father f){
((interfaceSon)f).fromInterSon();
System.out.println("--------"+f.toString());
//   3:  com.h.Son@1bab50a
System.out.println("--------"+f.getClass());
//   3:  class com.h.Son

/*        假如Son没有实现接口时,即:未标有  implements interfaceSon,
编译还是不会报错,但运行时会出现转换异常,
      ----:Son cannot be cast to interfaceSon
*/
}
}
public class TypeConvert{
public static void main(String args[]){
Son s = new Son();
Test t = new Test();
t.test1(s);
t.test2(s);
t.test3(s);

/*        Father f = new Father();
s = (Son)f;
     //4: java.lang.ClassCastException
*/
}
}


  强制类型转换:

   1  基本数据类型转换:
      一种是类型兼容的,那么Java 将自动地进行转换,
           如: form int to float
      另一种不兼容(缩小转换):一种增加()的显式的类型变换,
             如: int to byte ,(会%256变为byte) ,
             如: float to int (损失精度)

   2 引用数据类型转换:( 也为显示的类型转换)

      1 因为一旦一个对象创建了,对象的类型已经确定,
            也可以不用这个类型变量引用她,

       2.父类变量:
            用子类类型引用交给了父类变量,(上转型)
        但是你又想使用他原本的的特异功能,
            这个时候你可以又将其强转为子类,
         (但是如果对象本身就是父类类型,强转就会出错,见注释:4)

      3.接口变量引用:
         接口变量本身之只能通过实现它的类来获得其引用(接口回调)

   理解:

   1. 编译器值检查类型之间有无继承,或实现关系,有则通过;
          运行时则检查真正的类型,否则报错;

   2。由上面1 2 3 的注释,
      即使子类,或实现接口的类将引用给了其他变量来引用,
      但还是不会改变他原有属性, 一旦强转了,所引用的变量对原有的属性
      (如:son)将会选择性的拥有,

   3 假如将Son看做若干房间(方法看做房间)的拥有者,其包括:
      自己特有方法,实现接口的方法,继承父类的方法,
         (内存中也有未继承的方法)
     1. 父类只有父类的钥匙,
         只能开未继承的房间(自己的),继承或重写的,如:注释 0,
         ??---:test1()中f.fromFather()
         为什么结果会是fromFather2,,呵呵因为重写覆盖了了;
     2. 接口变量值拥有,开启实现的方法,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: