Reputation: 37
Why is it necesary to use Class class's methods to write classname.class.method or instance.getClass().method?
For example:
public class SomeClass{
public static void main (String[] args){
SomeClass sm = new SomeClass();
//The correct ways:
System.out.println(sm.getClass().getName());
//or
System.out.println(SomeClass.class.getName());
}
}
Class class's instance methods need a class (it can be seen when in System.out.println(sm.getClass().getName();
because sm.getClass() returns a class) so why is not correct to write System.out.println(SomeClass.getName();
and it is necessary to write "class" in the middle if getName() method is called by a class? Is it because SomeClass class is not considered an instance of Class class? Why sm.getClass() is considered an instance of Class class then?
Thank you.
Upvotes: 0
Views: 68
Reputation: 441
I am breaking the line to understand the easy way.Hope so it will be helpful
SomeClass sm = new SomeClass();
Class clazz1 = sm.getClass(); //sm.getClass() returns Class object
System.out.println(clazz1.getName());
Class clazz2 = SomeClass.class; //SomeClass.class returns Class object
System.out.println(clazz2.getName());
That means getName() method is available in Class class .
Upvotes: 0
Reputation: 131396
new SomeClass()
creates an instance of the SomeClass
class :
SomeClass someClass = new SomeClass();
It doesn't provide the Class
instance of SomeClass
as the getClass()
instance method of Object
class does :
Class<? extends SomeClass> clazz = new SomeClass().getClass();
These are two totally different things.
Upvotes: 4
Reputation: 62015
Why is it necesary to use Class class's methods to write classname.class.method or instance.getClass().method?
Java has no free-standing functions, so in order to invoke any function, you have to invoke it as a member of a class. And if you want to invoke a function that belongs to class A, you have to invoke it as a method of class A. I know this is a tautology; but this is what your question, as stated, calls for.
why is not correct to write System.out.println(SomeClass().getName();
It is not correct to write that, because it is not valid java syntax. Java reserves the class-name-followed-by-parentheses construct to stand for identifying constructors. (And it must be prefixed by new
.)
it is necessary to write "class" in the middle if getName() method is called by a class?
Besides not supporting free-standing functions, java does not support any free-standing code whatsoever, so in order to call anything, the calling code must be in a class, so all methods are called by a class.
Is it because SomeClass class is not considered an instance of Class class?
Uhm, yes.
Why sm.getClass() is considered an instance of Class class then?
It is not considered an instance of a class. But it does return an instance of a class.
Upvotes: 1