public class testinstanceof
{
  public static void main(String[] args)
  {  
    Object hello="hello";//hello 的实际类型是String
System.out.println("字符串是否是Object类的实例:" + (hello instanceof Object));
System.out.println("字符串是否是String类的实例:" + (hello instanceof String));
System.out.println("字符串是否为Math类的实例:" + (hello instanceof Math));
System.out.println("字符串是否为Comparable接口的实例:" + (hello instanceof Comparable));
  }
}
             
两个问题 1 第三个输出为什么是 false  ,按理说hello是Object类,是Math的父类应该是true的。
         2    第二个输出显示错误  拿错了?

解决方案 »

  1.   

    第三个 hello 是 Object 类型,虽说 Object 是 Math 的父类,但是 hello 不是 Math 类型啊。如果 instanceof 运算为 true 的话,那么就可以这样进行强制转换了:Math m = (Math)hello;
      

  2.   

    1.子类可以强制转换成父类,反之不行,所以字符串不是Math类的实例
    2.System.out.println("字符串是否是String类的实例:" + (hello instanceof String));
    就没问题了
      

  3.   

    1 第三个输出为什么是 false ,按理说hello是Object类,是Math的父类应该是true的---hello是object 单object不是hello