• Post Reply Bookmark Topic Watch Topic
  • New Topic

calling a non static method from a static method.  RSS feed

 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys this kind of confuses me because I read somewhere and even to my understanding that you can call a non static method from a static method IF an object of that class is instantiated,that's what I did but I am still gtting an error saying cannot make a static reference to the non static field hu


 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem you have is the Human object reference is stored in an instance variable so the static method can't access it. If variable 'hu' was static it would work.

I am assuming that code is just to test out the theory and not real code, I certainly wouldn't recommend making 'hu' static in real code.
 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey Tony thanks for the reply,

so it's actually possible to call a non static from a static method aslong as the instance that you are calling it from is static?

why is this possible?

and why can't you call a non static method from a static method if the instance isn't static?

thanks
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you have misunderstood what I was saying. The code provided would work if 'hu' was static but that doesn't mean that you can only a non static method from an instance in a static variable.

You could for example have your call method accept a Human instance as a parameter and use that instance to make the call to sayHi(). ie



 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Tony
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I personally think that is a misleading error message; it would be better if it said, “instance members can only be accessed from an instance context.” Keep quiet about static, because that can misdirect people into marking things static which shouldn't be static.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!