Java Object getClass()

The syntax of the getClass() method is:

object.getClass()

getClass() Parameters

The getClass() method does not take any parameters.


getClass() Return Values

  • returns the class of the object that calls the method

Example 1: Java Object getClass()

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {

    // getClass() with Object
    Object obj1 = new Object();
    System.out.println("Class of obj1: " + obj1.getClass());

    // getClass() with String
    String obj2 = new String();
    System.out.println("Class of obj2: " + obj2.getClass());

    // getClass() with ArrayList
    ArrayList<Integer> obj3 = new ArrayList<>();
    System.out.println("Class of obj3: " + obj3.getClass());
  }
}

Output

Class of obj1: class java.lang.Object
Class of obj2: class java.lang.String
Class of obj3: class java.util.ArrayList

In the above example, we have used the getClass() method to get the name of the class. Here, we are able to call the getClass() method using the String and ArrayList object.

It is because String and ArrayList inherit the Object class.


Example 2: Call getClass() from Custom Class

class Main {
  public static void main(String[] args) {

    // create an object of the Main class
    Main obj = new Main();

    // call getClass() method from Main
    System.out.println(obj.getClass()); 
  }
}

Output

class Main

Here, we have created a class named Main. Note that we have called the getClass() method using the method of Main.

It is possible because Object class is the superclass of all the classes in Java.

Note: The Object class is the superclass for all the classes in Java. Hence, every class can implement the getClass() method.

Did you find this article helpful?