JAVA中,instanceof的讲解
一 instanceof是java中的一个二元操作符。
二 instanceof的作用是测试它左边的对象是否是它右边类的实例,返回的是boolean类型的数据。他是判断对象是属于哪个类别的
举个例子
String st=”China”;
boolean judge=s instanceof st;
//此时judge的值为true 因为,st是Object类的一个实例
下面我们看一下关于instanceof的java程序:
有三个文件Phone.java,Apple.java,Instanceof.java
Phone.java
public class Phone {
public Phone(String num)
{
this.num=num;
}
public void setNum(String num)
{
this.num=num;
}
public String getNum(String num)
{
return num;
}
private String num;
}
Apple.java
public class Apple extends Phone{
public Apple(String num,double price)
{
super(num);
// TODO Auto-generated constructor stub
this.price=price;
}
public void setPrice(double price)
{
this.price=price;
}
public double getPrice()
{
return price;
}
public void gongneng()
{
System.out.println("苹果手机具有指纹功能");
}
private double price;
}
Instanceof2.java
public class Instanceof2
{
public static void main(String[] args)
{
int i=100;
int j=100;
String s1="一一一";
String s2="一一一";
String s3=new String("一一一");
String s4=new String("一一一");
Phone p1=new Phone("0001");
Phone p2=new Phone("0001");
Phone p3=p1;
Apple a=new Apple("0001",5000);
System.out.println("基本的类型比较如下: ");
System.out.print("i和j的比较: ");
System.out.println(i==j);
System.out.println("String的比较: ");
System.out.println("s1和s2的比较: ");
System.out.println("s1==s2: "+(s1==s2));
System.out.println("s1.equals(s2):" +(s1.equals(s2)));
System.out.println("s1==s3: "+(s1==s3));
System.out.println("s1.equals(s3): "+(s1.equals(s3)));
System.out.println("s3.equals(s4): "+(s3.equals(s4)));
System.out.println();
System.out.println("使用instanceof来比较");
System.out.println(a instanceof Phone);
if(a instanceof Apple)
{
a.gongneng();
}
else
{
System.out.println(a instanceof Apple);
};
System.out.println(p1 instanceof Phone);
System.out.println(p1 instanceof Apple);
System.out.println();
System.out.println("对象之间的比较: ");
System.out.println(p1==p3);
System.out.println(p1.equals(p3));
System.out.println(p1.equals(p2));
System.out.println(p1.hashCode()==p2.hashCode());
System.out.println(p1==p2);
}
}