What is the reason behind “non-static method cannot be referenced from a static context”? [duplicate]


What is the reason behind “non-static method cannot be referenced from a static context”? [duplicate]



This question already has an answer here:



The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message:



You can either make the non static method static or make an instance of that class to use its properties.



Why? I am not asking for solutions. I would be grateful to know what is the reason behind it. The very core reason!


private java.util.List<String> someMethod(){
/* Some Code */
return someList;
}

public static void main(String strArgs){
// The following statement causes the error. You know why..
java.util.List<String> someList = someMethod();
}



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.




13 Answers
13



You can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.





"Since you haven't created an object, the non-static method doesn't exist yet." -- Thank you very much. I should have thought of it.
– DragonBorn
Nov 14 '08 at 18:46





Method itself does exist. Somewhere in the loaded class definition. So the answer is wrong :)
– Vladimir Dyuzhev
Nov 14 '08 at 19:57





@Vladimir, OK if you want to be picky. :) "doesn't exist in current context" :)
– Brian Knoblauch
Nov 14 '08 at 20:26





"You can't call something that doesn't exist." - thug :p
– Anu Shibin Joseph Raj
Jan 18 '17 at 18:06





A static method cannot tell to which particular object the non-static member belongs to. Since there is no existing object, the non-static method doesn't belong to any object. Hence there is no way a non-static method can be referenced from static context.
– Saathvik
Feb 22 at 7:00


static


static



The method you are trying to call is an instance-level method; you do not have an instance.



static methods belong to the class, non-static methods belong to instances of the class.


static


static





"non-static methods belong to instances of the class" -- The answer. But why it belongs to the instance of the class? Thank you.
– DragonBorn
Nov 14 '08 at 18:09





@ZiG: because you told it to by not marking it static
– Steven A. Lowe
Nov 14 '08 at 19:04





For beginner developers, I have created an example to understand what @StevenA.Lowe mention above. repl.it/repls/WavyNeighboringSpotteddolphin
– supritshah1289
Dec 13 '17 at 15:14



The essence of object oriented programming is encapsulating logic together with the data it operates on.



Instance methods are the logic, instance fields are the data. Together, they form an object.


public class Foo
{
private String foo;
public Foo(String foo){ this.foo = foo; }
public getFoo(){ return this.foo; }

public static void main(String args){
System.out.println( getFoo() );
}
}



What could possibly be the result of running the above program?



Without an object, there is no instance data, and while the instance methods exist as part of the class definition, they need an object instance to provide data for them.



In theory, an instance method that does not access any instance data could work in a static context, but then there isn't really any reason for it to be an instance method. It's a language design decision to allow it anyway rather than making up an extra rule to forbid it.





the best answer
– Suganthan Madhavan Pillai
Mar 9 '15 at 4:38



I just realized, I think people shouldn't be exposed to the concept of "static" very early.



Static methods should probably be the exception rather than the norm. Especially early on anyways if you want to learn OOP. (Why start with an exception to the rule?) That's very counter-pedagogical of Java, that the "first" thing you should learn is the public static void main thing. (Few real Java applications have their own main methods anyways.)





I have encountered this problem with the error mentioned above, but must learn how to use static in order to use an instance of a class across different activities, so I am stuck struggling with it. :( trying so many things, but not working.
– Azurespot
May 5 '14 at 6:58



I think it is worth pointing out that by the rules of the Java language the Java compiler inserts the equivalent of "this." when it notices that you're accessing instance methods or instance fields without an explicit instance. Of course, the compiler knows that it can only do this from within an instance method, which has a "this" variable, as static methods don't.



Which means that when you're in an instance method the following are equivalent:


instanceMethod();
this.instanceMethod();



and these are also equivalent:


... = instanceField;
... = this.instanceField;



The compiler is effectively inserting the "this." when you don't supply a specific instance.



This (pun intended) bit of "magic help" by the compiler can confuse novices: it means that instance calls and static calls sometimes appear to have the same syntax while in reality are calls of different types and underlying mechanisms.



The instance method call is sometimes referred to as a method invocation or dispatch because of the behaviors of virtual methods supporting polymorphism; dispatching behavior happens regardless of whether you wrote an explicit object instance to use or the compiler inserted a "this.".



The static method call mechanism is simpler, like a function call in a non-OOP language.



Personally, I think the error message is misleading, it could read "non-static method cannot be referenced from a static context without specifying an explicit object instance".



What the compiler is complaining about is that it cannot simply insert the standard "this." as it does within instance methods, because this code is within a static method; however, maybe the author merely forgot to supply the instance of interest for this invocation — say, an instance possibly supplied to the static method as parameter, or created within this static method.



In short, you most certainly can call instance methods from within a static method, you just need to have and specify an explicit instance object for the invocation.



The answers so far describe why, but here is a something else you might want to consider:



You can can call a method from an instantiable class by appending a method call to its constructor,


Object instance = new Constuctor().methodCall();



or


primitive name = new Constuctor().methodCall();



This is useful it you only wish to use a method of an instantiable class once within a single scope. If you are calling multiple methods from an instantiable class within a single scope, definitely create a referable instance.



The compiler actually adds an argument to non-static methods. It adds a this pointer/reference. This is also the reason why a static method can not use this, because there is no object.


this pointer/reference. This is also the reason why a static method can not use this



If we try to access an instance method from a static context , the compiler has no way to guess which instance method ( variable for which object ), you are referring to. Though, you can always access it using an object reference.



A static method relates an action to a type of object, whereas the non static method relates an action to an instance of that type of object. Typically it is a method that does something with relation to the instance.



Ex:



class Car might have a wash method, which would indicate washing a particular car, whereas a static method would apply to the type car.





Not all methods have side-effects! Doesn't have to be an action to, it could just as well be something that the object tells you.
– Hugo
Nov 15 '08 at 7:30



if a method is not static, that "tells" the compiler that the method requires access to instance-level data in the class, (like a non-static field). This data would not be available unless an instance of the class has been created. So the compiler throws an error if you try to call the method from a static method.. If in fact the method does NOT reference any non-static member of the class, make the method static.



In Resharper, for example, just creating a non-static method that does NOT reference any static member of the class generates a warning message "This method can be made static"



The simple reason behind this is that Static data members of parent class
can be accessed (only if they are not overridden) but for instance(non-static)
data members or methods we need their reference and so they can only be
called through an object.



So you are asking for a very core reason?



Well, since you are developing in Java, the compiler generates an object code that the Java Virtual Machine can interpret. The JVM anyway is a binary program that run in machine language (probably the JVM’s version specific for your operating system and hardware was previously compiled by another programming language like C in order to get a machine code that can run in your processor). At the end, any code is translated to machine code. So, create an object (an instance of a class) is equivalent to reserve a memory space (memory registers that will be processor registers when the CPU scheduler of the operating system put your program at the top of the queue in order to execute it) to have a data storage place that can be able to read and write data. If you don’t have an instance of a class (which happens on a static context), then you don’t have that memory space to read or write the data. In fact, like other people had said, the data don’t exist (because from the begin you never had written neither had reserved the memory space to store it).



Sorry for my english! I'm latin!



A non-static method is dependent on the object. It is recognized by the program once the object is created.



Static methods can be called even before the creation of an object. Static methods are great for doing comparisons or operations that aren't dependent on the actual objects you plan to work with.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV