Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getClass method in java

Tags:

java

How is it that the getClass method in Object class is capable of dynamically returning Class?

like image 864
abson Avatar asked Oct 19 '25 01:10

abson


1 Answers

It doesn't return the class name - it returns the Class representing that object's type. Each object "knows" what type it really is - that's how casts can work or fail depending on the execution-time type. Object.getClass() just retrieves the relevant information from the object.

If you have a class which only contains a single int, each object will still take up more than 4 bytes in memory: there's effectively an object "header" containing things like a reference to the object's actual type, information to do with the monitor associated with that object etc.

like image 158
Jon Skeet Avatar answered Oct 21 '25 14:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!