English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Online tools

each loop

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Exception Handling

resources

Java List (List)

Java Queue (queue)

Java Map Collection

Java Set Collection/Java Input Output(I

Java O Stream/Java Reader

Writer

New feature

Java Examples Comprehensive

Java program checks the class of an object obtained

In this example, we will learn to use the getClass() method, instanceof operator, and isInstance() method to determine the class of an object in Java.To understand this example, you should understand the followingJava programming

Example1Java instanceof

: Use getClass() to check the class of an object1 class Test
// first class
}
: Use getClass() to check the class of an object2 class Test
// {
}
class Main {
  public static void main(String[] args) {
    //second class
    create an object1 obj1 Test1= new Test
    create an object2 obj2 Test2= new Test
    // ();1gets the object obj
    System.out.print("obj1is: ");
    System.out.println(obj1.getClass());
    // ();2gets the object obj
    System.out.print("obj2is: ");
    System.out.println(obj2.getClass());
  }
}

Output Result

obj1is: class Test1
obj2is: class Test2

In the above example, we used the getClass() method of the Object class to get the class of the object obj1and obj2for the class name.

For more information, please visitJava Object getClass().

Example2: Use the instanceof operator to check the class of an object

class Test {
// class
}
class Main {
  public static void main(String[] args) {
    //Create an object
    Test obj = new Test();
    // Check if obj is an object of Test
    if(obj instanceof Test) {
      System.out.println("obj is an instance of the Test class");
    }
    else {
      System.out.println("obj is not an instance of the Test class");
    }
  }
}

Output Result

obj is an instance of the Test class

In the above example, we use the instanceof operator to check if the object obj is an instance of Test.

Example3: Check the class of the object using isInstance()

class Test {
// first class
}
class Main {
  public static void main(String[] args) {
    //Create an object
    Test obj = new Test();
    //Check if obj is an instance of Test1object
    if (Test.class.isInstance(obj)) {
      System.out.println("obj is an instance of the Test class");
    }
    else {
      System.out.println("obj is not an instance of the Test class");
    }
  }
}

Output Result

obj is an instance of the Test class

In this example, we use the isInstance() method of the Class class to check if the object obj is an instance of the Test class.

The working principle of the isInstance() method is similar to the instanceof operator. However, it is best to use it at runtime.

Java Examples Comprehensive