📜  Java中的instanceof关键字

📅  最后修改于: 2022-05-13 01:55:19.304000             🧑  作者: Mango

Java中的instanceof关键字

instanceof 是一个关键字,用于检查引用变量是否包含给定类型的对象引用。下面是一个Java程序来展示 instanceof 的不同行为。此后,它被称为运算符,其中实例与返回布尔值 true 或 false 的类型进行比较,因为在Java中我们没有 0 和 1 布尔返回类型。

例子:

Java
// Java Program to Illustrate instanceof Keyword
 
// Importing required I/O classes
import java.io.*;
 
// Main class
class GFG {
    public static void main(String[] args)
    {
 
        // Creating object of class inside main()
        GFG object = new GFG();
 
        // Returning instanceof
        System.out.println(object instanceof GFG);
    }
}


Java
// Java program to demonstrate working of instanceof Keyword
 
// Class 1
// Parent class
class Parent {}
 
// Class 2
// Child class
class Child extends Parent {}
 
// Class 3
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating object of child class
        Child cobj = new Child();
 
        // A simple case
        if (cobj instanceof Child)
            System.out.println("cobj is instance of Child");
        else
            System.out.println(
                "cobj is NOT instance of Child");
 
        // instanceof returning true for Parent class also
        if (cobj instanceof Parent)
            System.out.println(
                "cobj is instance of Parent");
        else
            System.out.println(
                "cobj is NOT instance of Parent");
 
        // instanceof returns true for all ancestors
 
        // Note : Object is ancestor of all classes in Java
        if (cobj instanceof Object)
            System.out.println(
                "cobj is instance of Object");
        else
            System.out.println(
                "cobj is NOT instance of Object");
    }
}


Java
// Java program to demonstrate that instanceof
// returns false for null
 
class Test {  }
 
class Main
{
    public static void main(String[] args)
    {
        Test tobj = null;
 
        // A simple case
        if (tobj instanceof Test)
           System.out.println("tobj is instance of Test");
        else
           System.out.println("tobj is NOT instance of Test");
    }
}


Java
// A Java program to show that a parent object is
// not an instance of Child
 
class Parent {  }
class Child extends Parent { }
 
class Test
{
    public static void main(String[] args)
    {
        Parent pobj = new Parent();
        if (pobj instanceof Child)
           System.out.println("pobj is instance of Child");
        else
           System.out.println("pobj is NOT instance of Child");
    }
}


Java
// A Java program to show that a parent reference
// referring to a Child is an instance of Child
 
class Parent {  }
class Child extends Parent { }
 
class Test
{
    public static void main(String[] args)
    {
        // Reference is Parent type but object is
        // of child type.
        Parent cobj = new Child();
        if (cobj instanceof Child)
           System.out.println("cobj is instance of Child");
        else
           System.out.println("cobj is NOT instance of Child");
    }
}


Java
// Java program to demonstrate that non-method
// members are accessed according to reference
// type (Unlike methods which are accessed according
// to the referred object)
 
class Parent
{
    int value = 1000;
}
 
class Child extends Parent
{
    int value = 10;
}
 
// Driver class
class Test
{
    public static void main(String[] args)
    {
        Parent cobj = new Child();
        Parent par = cobj;
 
        // Using instanceof to make sure that par
        // is a valid reference before typecasting
        if (par instanceof Child)
        {
            System.out.println("Value accessed through " +
                "parent reference with typecasting is " +
                                     ((Child)par).value);
        }
    }
}


输出
true

实现:在这里,我们将创建具有父子关系的示例类。

示例 1:

Java

// Java program to demonstrate working of instanceof Keyword
 
// Class 1
// Parent class
class Parent {}
 
// Class 2
// Child class
class Child extends Parent {}
 
// Class 3
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating object of child class
        Child cobj = new Child();
 
        // A simple case
        if (cobj instanceof Child)
            System.out.println("cobj is instance of Child");
        else
            System.out.println(
                "cobj is NOT instance of Child");
 
        // instanceof returning true for Parent class also
        if (cobj instanceof Parent)
            System.out.println(
                "cobj is instance of Parent");
        else
            System.out.println(
                "cobj is NOT instance of Parent");
 
        // instanceof returns true for all ancestors
 
        // Note : Object is ancestor of all classes in Java
        if (cobj instanceof Object)
            System.out.println(
                "cobj is instance of Object");
        else
            System.out.println(
                "cobj is NOT instance of Object");
    }
}
输出
cobj is instance of Child
cobj is instance of Parent
cobj is instance of Object

示例 2: instanceof 为 null 返回 false

Java

// Java program to demonstrate that instanceof
// returns false for null
 
class Test {  }
 
class Main
{
    public static void main(String[] args)
    {
        Test tobj = null;
 
        // A simple case
        if (tobj instanceof Test)
           System.out.println("tobj is instance of Test");
        else
           System.out.println("tobj is NOT instance of Test");
    }
}

输出:

tobj is NOT instance of Test

示例 3:父对象不是 Child 的实例

Java

// A Java program to show that a parent object is
// not an instance of Child
 
class Parent {  }
class Child extends Parent { }
 
class Test
{
    public static void main(String[] args)
    {
        Parent pobj = new Parent();
        if (pobj instanceof Child)
           System.out.println("pobj is instance of Child");
        else
           System.out.println("pobj is NOT instance of Child");
    }
}

输出:

pobj is NOT instance of Child

示例 4:引用 Child 的父引用是 Child 的一个实例

Java

// A Java program to show that a parent reference
// referring to a Child is an instance of Child
 
class Parent {  }
class Child extends Parent { }
 
class Test
{
    public static void main(String[] args)
    {
        // Reference is Parent type but object is
        // of child type.
        Parent cobj = new Child();
        if (cobj instanceof Child)
           System.out.println("cobj is instance of Child");
        else
           System.out.println("cobj is NOT instance of Child");
    }
}

输出:

cobj is an instance of Child

现在, instanceof关键字的应用如下:

我们在这里看到,当父类型的引用引用子对象时,会访问父类数据成员。我们可以使用类型转换访问子数据成员。

句法:

((child_class_name) Parent_Reference_variable).func.name()

当我们进行类型转换时,检查类型转换是否有效总是一个好主意。 instanceof 在这里帮助我们。我们总是可以首先使用 instancef 检查有效性,然后进行类型转换。

例子

Java

// Java program to demonstrate that non-method
// members are accessed according to reference
// type (Unlike methods which are accessed according
// to the referred object)
 
class Parent
{
    int value = 1000;
}
 
class Child extends Parent
{
    int value = 10;
}
 
// Driver class
class Test
{
    public static void main(String[] args)
    {
        Parent cobj = new Child();
        Parent par = cobj;
 
        // Using instanceof to make sure that par
        // is a valid reference before typecasting
        if (par instanceof Child)
        {
            System.out.println("Value accessed through " +
                "parent reference with typecasting is " +
                                     ((Child)par).value);
        }
    }
}

输出:

Value accessed through parent reference with typecasting is 10