• Post Reply Bookmark Topic Watch Topic
  • New Topic

Not able to call getClass() in a method  RSS feed

 
pramod talekar
Ranch Hand
Posts: 367
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Could you please tell me why we can't call getClass() method inside the main method.
The error message is "Can not make a static call to the non static method."

If this is the case then how I'm able to call it in the first statement after class declaration.



 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getClass returns the runtime class of an object...but you don't HAVE an object.

What exactly would you expect it to return?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whereas on line 5...that's a non-static member, so it only gets executed if an instance of the class is created. In which case you now have an object to call it on!
 
pramod talekar
Ranch Hand
Posts: 367
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Matthew & Fred.

I understood line no. 9 reason but not no.5.

Where's the object to call?
Matthew, could you please explain.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Forget it. Out to lunch.

Winston
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's the implicit this you're calling getClass() on. In other words, the current instance.
 
pramod talekar
Ranch Hand
Posts: 367
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok, and the implicit object this isn't available in main,right?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no object in main. a 'static' method can be called even if there is no object.

But the only way your line 5 will run is when you are instantiating/creating the object, therefore you will have one.
 
pramod talekar
Ranch Hand
Posts: 367
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Fred / fred(lowercase),

I'understood about line no. 5 completely. It's an instance variable which can only be executed with an object of the containing class.

Now for line no. 9, Had I written , then it'd have worked.

Thanks. You rock.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!