public class Test {
public static void main(String[] args)
{
Object obj = new String();
System.out.println(obj instanceof String);
System.out.println(obj instanceof Integer);
System.out.println(obj instanceof Book);
}
class Book
{
}
}
public static void main(String[] args)
{
Object obj = new String();
System.out.println(obj instanceof String);
System.out.println(obj instanceof Integer);
System.out.println(obj instanceof Book);
}
class Book
{
}
}
结果为:true,false,false
但是如果这样写则不会通过编译:
System.out.println(new Integer() instanceof String);
本文通过一个简单的Java程序示例,展示了如何使用instanceof关键字来进行类型检查。程序创建了一个String对象并将其赋值给Object类型的变量,然后分别检查该对象是否为String、Integer及自定义Book类的实例。
1501

被折叠的 条评论
为什么被折叠?



