0

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

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 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 http://stackoverflow.com/questions/5201895/calling-the-instance-of-a-static-method?rq=1 , http://stackoverflow.com/questions/18375971/can-i-call-instance-method-of-a-static-member-from-within-static-context?rq=1 (or this) possible duplicate of [What is the reason behind "non-static method cannot be referenced from a static context"?](http://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static) – user2864740 Apr 19 '14 at 20:22

2 Answers2

1

Here is a nice code piece to illustrate what it means:

class MyClass{

    static void func1(){
        func2(); //This will be an error
    }

    void func2(){
        System.out.println("Hello World!");
    }

}
ASKASK
  • 657
  • 8
  • 16
0

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();
}
DNA
  • 42,007
  • 12
  • 107
  • 146