Determine the class of an object

Check the class of an object using getClass()

class Test1 {
// first class
}

class Test2 {
// second class
}


class Main {
  public static void main(String[] args) {
    // create objects
    Test1 obj1 = new Test1();
    Test2 obj2 = new Test2();

    // get the class of the object obj1
    System.out.print("The class of obj1 is: ");
    System.out.println(obj1.getClass());

    // get the class of the object obj2
    System.out.print("The class of obj2 is: ");
    System.out.println(obj2.getClass());
  }
}

Output

The class of obj1 is: class Test1
The class of obj2 is: class Test2

In the above example, we have used the getClass() method of the Object class to get the class name of the objects obj1 and obj2.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *