getClass( ) method is one of the Object Class methods. As all the other Classes in Java are the sub classes of the Object Class, any Class can access this method using its object.
getClass( ) method returns the run time class name of the object.
Syntax of getClass( ) method -
ClassOne object1 = new ClassOne( );
object1.getClass( ); //Returns the run time class name of the object 'object1'
When you print the above statement it will give the output as class ClassOne.
This is how getClass( ) method of Object Class works.
Lets implement getClass( ) method on Eclipse IDE -
1. Launch Eclipse IDE, create a Java Project 'Project 35' as shown below -
2. Create a Java Class file 'ClassXYZ' with main( ) method as shown below -
3. Create a Class 'ClassOne' in the same Class file 'ClassXYZ' as shown below -
4. Create an object for ClassOne in the 'ClassXYZ' as shown below -
5. Print the Class name of the 'object1' object using the getClass( ) method as shown below -
6. Save & Run the Class file 'ClassXYZ' and view the output in the Eclipse IDE console as shown below -
Hence the class name of the object 'object1' i.e. ClassOne is displayed in the output as shown above.
Now lets use an object of the predefined Class like String to print the Class name using getClass( ) method by following the below steps.
7. Create a String object with a value as shown below -
8. Print the Class Name of the string object 'str' using getClass( ) method as shown below -
9. Save & Run the Java Class file 'ClassXYZ' and view the output in the console as shown below-
Observe that the String Class Name along with its path is displayed in the output as shown above.
Hence getClass( ) method returns the Class Name of any object.
Please comment below to feedback or ask questions.