2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

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

It"s 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.

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();           
}
userimage

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.

userimage

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.

Answer is