instanceof简单用法

语法: 对象 instanceof 类; 

含义:如果这个对象时这个类或者这个类的子类的实例化,那么结果及时ture, 否则 false。

常常用来判断一个类是否是某个类的子类,以此判断A类是否继承或者间接继承B类。

 

实例1:

一、对象A是类B的子类的实例化对象

package equalsTest;

public class Test00
{
	public static void main(String[] args)
	{
		Father f = new Father();
		User1 u1 = new User1();
		User2 u2 = new User2();
		
		//u1对象是Father类的子类的实例化,所以返回ture
		if(u1 instanceof Father)
		{
			System.out.println("ture");			
		}
		else System.out.println("flase");
	}
}


//父类
class Father {}

//子类1
class User1 extends Father {}

//子类2
class User2 extends Father {} 

此时返回的结果就是ture;u1对象是不是Father类的实例化,但是是Father子类的实例化,所以是ture

 

二、如果是下面这种情况:

如果返过来,父类的对象 instanceof 子类

	if(f instanceof User1)
		{
			System.out.println("ture");			
		}
		else System.out.println("flase");

结果是false; 此时f不是User1类的实例化对象,同时也是不是User1子类的实例化对象,所以false。

 

三、两个类有间接继承关系

package equalsTest;

public class Test00
{
    public static void main(String[] args)
    {
        
        Father f = new Father();
        User1 u1 = new User1();
        User2 u2 = new User2();
        
        //u1对象是Father类的子类的实例化,所以返回ture
        if(u2 instanceof Father)
        {
            System.out.println("ture");            
        }
        else System.out.println("flase");
    }
}


//父类
class Father {}

//子类1
class User1 extends Father {}

//子类2间接继承Father
class User2 extends User1 {}

此时结果是:ture; 所以如果对象时这个类的实例化,或者子类的实例化,或者子类的子类的实例化。

所以任何对象 instanceof Object都是ture

 

posted on 2019-03-31 17:35  jesse_zhao  阅读(611)  评论(0编辑  收藏  举报

导航