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()
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
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.