Forums Register Login

non-static method can't be referenced from static context

+Pie Number of slices to send: Send


But Method can be accessed via object of the class, why is it so, please guide me with a brief explanation ?

 
+Pie Number of slices to send: Send
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).
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
 

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++

 
+Pie Number of slices to send: Send
 

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.
+Pie Number of slices to send: Send
 

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();
+Pie Number of slices to send: Send
 

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!!!
We can fix it! We just need some baling wire, some WD-40, a bit of duct tape and this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 4611 times.
Similar Threads
doubt on thread
Question about Threads
doubt on thread
need explanation
Threads doubt??
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 09:54:42.