引用变量只能调用它编译时的类型方法,而不能调用它运行时类型的方法。
强制类型转换:
1.基本类型之间的转换只能在数值类型之间进行。数值类型与布尔类型不能转换。
2.引用类型之间的转换只能在具有继承关系的两个类型之间进行,如果试图把一个父类实例转换为一个子类类型,则这个对象必须实际上是子类类型(即编译时时父类类型,而运行时为子类类型),否则会ClassCastException。
//类型转换
double d=13.12;
long l=(long)d;
System.out.println(l);
//编译时会提示不可转换类型
//boolean b=(boolen) d;
Object b="hello";
String bi=(String) b;
System.out.println(bi);
Object c=new Integer(5);
Integer co=(Integer)c;
System.out.println(co);
String ci=(String)c;
最后一行强制类型转换会出错。因为c不是String类型,不能转化为String类型。
当子类对象赋给父类引用便量是,成为向上转型。这种类型转换总是成功的,这也证实,子类是一种特殊的父类。
但把一个父亲对象赋给子类引用变量时,就需要进行强制类型转换,而且可能产生ClassCastException异常,使用instanceof运算符可以让强制转换类型更安全。
instanceof运算符的前一个操作数是一个引用类型变量,后一个操作数是通常是一个类。它用于判断前面的对象是否是 后面的类,或者其子类、实现类的实例。是则返回true,否返回false
System.out.println("是否是Objece类"+(b instanceof Object));//true
System.out.println("是否是String类"+(b instanceof String));//true
System.out.println("是否是Integer类"+(b instanceof Integer));//false
System.out.println("是否是Comparable接口"+(b instanceof Comparable));//true