| Author |
non-static method can't be referenced from static context
|
Himanshu V Singh
Greenhorn
Joined: May 06, 2011
Posts: 17
|
|
But Method can be accessed via object of the class, why is it so, please guide me with a brief explanation ?
|
 |
Jared Malcolm
Ranch Hand
Joined: May 02, 2011
Posts: 54
|
|
You first have to instantiate the class TryCatchTest in order to access a non static member. Just the rules of Java....a static member can't access a non static one. so....
For me though I generally just make a constructor to take the place of the run method. Just gets rid of some unneeded code (in my mind anyway).
|
SCJA 6 (Studying for SCJP 6)
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9939
|
|
|
in your example, you haven't created an instance of your class. Therefore, "[The] Method can be accessed via object of the class" is irrelevant.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Himanshu V Singh
Greenhorn
Joined: May 06, 2011
Posts: 17
|
|
Jared Malcolm wrote:You first have to instantiate the class TryCatchTest in order to access a non static member. Just the rules of Java....a static member can't access a non static one. so....
For me though I generally just make a constructor to take the place of the run method. Just gets rid of some unneeded code (in my mind anyway).
But within same class, cant i access methods with out using object of class like c++
|
 |
Rupesh Mhatre
Ranch Hand
Joined: Apr 29, 2011
Posts: 35
|
|
Himanshu V Singh wrote:
But Method can be accessed via object of the class, why is it so, please guide me with a brief explanation ?
It has very simple reason static members are class level members and you don't need instance for that and non static members are instance specific so they need instance to get called so in your case if run method had been static method then you could use it without creating any instance like TryCatchTest.run();. Now as your run method is not static so it is a instance specific method so when you call it from static method i.e. main method you get compiler error saying non-static method can't be referenced from static context. I guess this will help.
|
 |
Jared Malcolm
Ranch Hand
Joined: May 02, 2011
Posts: 54
|
|
Rupesh Mhatre wrote:TryCatchTest.run();
If the run method had been static there would be no reason to even put the TryCatchTest in there........could have simply put run();
|
 |
jishnu dasgupta
Ranch Hand
Joined: Mar 11, 2011
Posts: 103
|
|
Himanshu V Singh wrote:
But within same class, cant i access methods with out using object of class like c++
Please get rid of this idea of comparing c++ and java.Trust me they are way different although it might seem they have loads of similarities, and are OOP languages!!!
|
If debugging is the process of removing bugs, then programming must be the process of putting them in. -- Edsger Dijkstra
|
 |
 |
|
|
subject: non-static method can't be referenced from static context
|
|
|