getclass() in Java
Overview
getClass() in Java is a method of the Object class present in java.lang package. getClass() returns the runtime class of the object "this". This returned class object is locked by static synchronized method of the represented class.
Syntax of getClass() in Java
Method signature for the function is:
The syntax for calling the getClass() method is:
Here, "obj" is the name of the object upon which you would call the method.
Parameters of getClass() in Java
The getClass method does not take in any parameters.
Return value of getClass() in Java
The getClass method returns the runtime class of the object "this". For example, suppose we call getClass() on an object obj (as demonstrated in code snippet above), the return value of the getClass() will be the class of which this is an object of. "this" in this case is our object obj itself. The class object that is returned is locked by the static synchronized method of the represented class.
Exceptions of getClass() in Java
getClass() does not throw any exceptions.
What is getClass() in Java?
The Object.getClass() method is called upon an instance of a class. If we have an object, we can call object.getClass() to determine the Class of the object. But we can not similarly use the Object.getClass() method upon abstract classes, or interfaces. We can not use getClass on primitive data types either.
Examples of getClass() in Java
Example 1: Calling lang.Object.getClass() method on Object class
Output::
We instantiate 3 objects of different classes, one of data type Object, String, and ArrayList each. Then we will call getClass() on each of these objects we created.
Example 2: Calling getClass() from a custom class
Outputs:
In the code snippet above, we instantiate an object "main" of our Main class. Then call the getClass method on the main object, to obtain its class name.
Note: The Object class is the superclass for all the classes in Java. Hence, every class can implement the getClass() method.
Conclusion
- getClass() method returns the runtime class of the object "this".
- The object that getClass() returns, is locked by static synchronized method of the represented class.