Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you call a non-static method from a static method?

I have a static method [Method1] in my class, which calls another method [Method2] in the same class and is not a static method. But this is a no-no. I get this error:

An object reference is required for the non-static field, method, or property "ClassName.MethodName()"

Can someone please briefly describe why? including other things that might be related to this.

like image 666
VoodooChild Avatar asked Jun 10 '10 19:06

VoodooChild


People also ask

Why we Cannot call non-static method from static method Java?

You cannot call non-static methods or access non-static fields from main or any other static method, because non-static members belong to a class instance, not to the entire class.

How do you call a non-static method from a static class?

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself. Save this answer.

Can we call a non-static variable in static method?

Yes, a static method can access a non-static variable. This is done by creating an object to the class and accessing the variable through the object.

Can we call non-static method from main method?

To call a non-static method from main in Java, you first need to create an instance of the class, post which we can call using objectName. methodName().


2 Answers

A non-static method requires an instance of the class. Unless you have passed in an instance, or created an instance in your method, you cannot call a non-static method, as you have no idea what instance of the class that method should operate on.

like image 171
Yann Ramin Avatar answered Oct 20 '22 19:10

Yann Ramin


Within a static method, you do not have an instance of the class. So it will be impossible to call an instance method on an instance when no instance exists.

like image 33
Wallace Breza Avatar answered Oct 20 '22 18:10

Wallace Breza