It is said in java that we can not call a non-static method from a static method..what does this mean exactly ?we can always call a non static method frm static one using object although..'pls explan
-
Write code that tries to do what is reported to can't be done. Then search for the error message. You will find many duplicates like stackoverflow.com/questions/5201895/… , stackoverflow.com/questions/18375971/… (or this) possible duplicate of What is the reason behind "non-static method cannot be referenced from a static context"?user2864740– user28647402014-04-19 20:22:41 +00:00Commented Apr 19, 2014 at 20:22
Add a comment
|
2 Answers
To call a non-static method, you need an instance (object) - because these methods belong to an instance, and in general only make sense in the context of an instance.
Static methods don't belong to an instance - they belong to the class. So there is no need to create an instance first, you can just call MyClass.doSomething()
void foo(){
MyClass.doSomething();
}
But you can call a non-static method from a static method provided you first create an instance.
static void bar(){
MyObject o = new MyObject();
o.doSomething();
}