abson
abson

Reputation: 9348

getClass method in java

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

Upvotes: 4

Views: 1203

Answers (2)

user207421
user207421

Reputation: 310893

And there's nothing dynamic about it. The class of the object can never change.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500495

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.

Upvotes: 11

Related Questions