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.
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.
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.
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.
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().
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With