天天看点

学习笔记——instanceof关键字

**向下转型存在安全隐患,为了保证向下转型安全性,通过instanceof关键字进行判断某个实例是否是某个类的对象。**语法定义如下:

对象 instanceof 类

该对象返回一个boolean类型,如果返回值为true则表示实例是指定对象。

例子:观察instanceof关键字使用1

class Person{
    public  void print(){
    System.out.println("吃饭、睡觉、学习、工作...");
       }
}
class Per extends Person{
	public String fly(){
	return "飞翔、";
		}
	public String wound(){
	return "能打";
		}
}
public class Lx {
	   public static void main(String[] args){
			 Person a=new Person();//不转型
			 System.out.println(a instanceof Person);//输出true
			 System.out.println(a instanceof Per);//输出false
		    }
}
           

如果不采用向上转型,那么实例化后的这对象就是一个普通人person,即实例化对象a为普通人;

a instanceof Person:表示a是person普通人,//输出true

a instanceof Per;表示a是per超人,//输出false

例子:观察instanceof关键字使用2

public static void main(String[] args){
 Person a=new Per();//向上转型
 System.out.println(a instanceof Person);//true
 System.out.println(a instanceof Per);//true
 }
           

日后项目开发过程中,如果要进行向下转型,先使用instanceof进行判断。

例子:

class Person{
    public  void print(){
    System.out.println("吃饭、睡觉、学习、工作...");
       }
}
class Per extends Person{
	public String fly(){
	return "飞翔、";
		}
	public String wound(){
	return "能打";
		}
}
public static void main(String[] args){
 Person a=new Per();//向上转型
 if(a instanceof Per){ //判断是否已经向上转型,即a是否为隐藏超人
 Per b=(Per) a;
 System.out.println(b.fly());
 System.out.println(b.wound());
 }
 }
           

输出结果:

飞翔

能打

向上转型以后就表示实例化对象a是一个隐藏在普通人里面的超人,除了具有自己作为person的属性之外,还具有作为per的属性。

继续阅读