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
62.5k15 gold badges159 silver badges234 bronze badges
asked Apr 19, 2014 at 20:13
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!");
 }
}
answered Apr 19, 2014 at 20:16
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();
}
answered Apr 19, 2014 at 20:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.