What is the reason behind "non-static method cannot be referenced from a static context"?

JavaStatic

Java Problem Overview


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.

What the reason behind this? Am not concern with the solution, rather the reason.

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

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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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.)

Solution 5 - Java

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.

Solution 6 - Java

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.

Solution 7 - Java

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.

Solution 8 - Java

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.

Solution 9 - Java

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"

Solution 10 - Java

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.

Solution 11 - Java

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!

Solution 12 - Java

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.

Solution 13 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSajal DuttaView Question on Stackoverflow
Solution 1 - JavaBrian KnoblauchView Answer on Stackoverflow
Solution 2 - JavaSteven A. LoweView Answer on Stackoverflow
Solution 3 - JavaMichael BorgwardtView Answer on Stackoverflow
Solution 4 - JavaHugoView Answer on Stackoverflow
Solution 5 - JavaErik EidtView Answer on Stackoverflow
Solution 6 - JavaAnde TurnerView Answer on Stackoverflow
Solution 7 - JavaVivek VermaniView Answer on Stackoverflow
Solution 8 - JavaRobinView Answer on Stackoverflow
Solution 9 - JavaCharles BretanaView Answer on Stackoverflow
Solution 10 - JavaantiparagonView Answer on Stackoverflow
Solution 11 - JavaCristián MunizagaView Answer on Stackoverflow
Solution 12 - JavaVipulView Answer on Stackoverflow
Solution 13 - JavaEjesalvaView Answer on Stackoverflow