I am a newbie and I have covered all the basic concepts of Java. Till now, I have come across examples where object references are created using Object class and using the “.class” syntax.
I tried searching for explanation on how these 2 concepts are used and I am not getting a clear picture.
All I see is, yes we can create a reference to Object. But how/what is this reference used for?
And for .class syntax, I keep seeing the term ‘Reflection’ but what really happens when I use this syntax on an exsting class like existingclass.class? And is it just to use the methods/data with in the <existingclass> without creating an instance/object?
Examples would be appreciated.
A reference to
Objectcan point to any object; it can point to different kinds of objects at different times. It’s a good parameter type for a method when you want to pass in any kind of object, and it’s a good return type when you want to be able to return any kind of object.The notation ClassName
.classreturns an instance ofjava.lang.Classwhich represents ClassName. For every class loaded in the Java virtual machine, there is ajava.lang.Classobject to represent that class. As to what it’s good for — it’s only good for fairly advanced, magical stuff like writing code that asks what methods a class has, or creating an instance of a class when all you have is the name of the class typed in by a user or read from a file.Also, when you learn about threads, you’ll see that the class object has a special purpose wih respect to static methods; this need not concern you now. As a beginning Java programmer, you’ll have no need to use it; someday, though, you may.