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

1

2 Answers 2

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!");
    }

}
Sign up to request clarification or add additional context in comments.

Comments

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.