instanceof instanceof是Java的一个二元操作符,和==,>,<是同一类东西。由于它是由字母组成的,所以也是Java的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回boolean类型的数据。举个例子:
String s = "I AM an Object!";
boolean isObject = s instanceof Object;
给出个例题: class Animal{
public String name ;
public Animal(String name){
this.name=name;
}
}
class Dog extends Animal{
public String furcolor;
public Dog(String n,String furcolor){
super(n);this.furcolor=furcolor;
}
}
class Cat extends Animal{
public String eyecolor;
public Cat(String n,String eyecolor){
super(n);this.eyecolor=eyecolor;
}
}
public class Test{
public static void main(String args[]){
Animal a= new Animal("name");
Cat cat=new Cat("xiaohua","blue");
Dog dog=new Dog("xiaohuang","Yellow");
System.out.println(a instanceof Animal);
System.out.println(cat instanceof Animal);
System.out.println(dog instanceof Animal);
System.out.println(a instanceof Cat);
a=new Dog("BigYellow","Yellow");
System.out.println(a.name);
Dog b=(Dog)a;
System.out.println(b.furcolor);
}
}
Tags -
java
文章来源:
http://www.tt-shopping.com/kevinlau/read.php/110.htm