Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please help on Static Method

 
Kumanan Guna
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm preparing for OCPJP 6 exam and study guide as K&B book.

One of the question as calling non-static method from main static method. But as per my understanding we cannot call non-static method from static method.
As main method is a static, would like to know how below example works fine.

Method go() is non-static method, but we are calling that method from main static method.

Please help me on this.

 
adil zahir
Greenhorn
Posts: 29
Chrome Java ME Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
first you need to understand what that mean


we can write that in this way

we create Object Zookeeper and we use p reference to point to the Object Zookeeper , now we will invoke the method go() .
yes we can't call no-static method directly from static method but we can use instance Object ( create Object the same way we did in the example "Zookeeper p = new Zookeeper(); " ) to call the no-static method " p.go() "
 
Kumanan Guna
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Zahir...
Yes, I did trail and error by calling the go() method directly and got an expected error "cannot make a reference to static from non-static method".
so, only through the instance object non-static method can be invoked from static methods.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic