Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java. getClass() returns a class, how come I can get a string too?

Tags:

java

When I use System.out.println(obj.getClass()) it doesn't give me any error. From what I understand getClass() returns a Class type. Since println() will print only strings, how come instead of a class, println is getting a String?

like image 292
Carlo Luther Avatar asked May 05 '13 14:05

Carlo Luther


People also ask

Does getClass return string?

As you probably know, every class in Java inherits from the Object class. This means that every class automatically has the method toString() , which returns a representation of the object as a String .

What does getClass () do in Java?

getClass() method returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.

What does getClass () getName () Do Java?

Java Class getName() Method The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object.

How does the getClass method work?

getClass() is the method of Object class. This method returns the runtime class of this object. The class object which is returned is the object that is locked by static synchronized method of the represented class.


1 Answers

System.out.println(someobj) is always equivalent to:

System.out.println(String.valueOf(someobj));

And, for non-null values of someobj, that prints someobj.toString();

In your case, you are doing println(obj.getClass()) so you are really doing:

System.out.println(String.valueOf(obj.getClass()));

which is calling the toString method on the class.

like image 135
rolfl Avatar answered Oct 07 '22 21:10

rolfl