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

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

You cant call something that doesnt exist. Since you havent created an object, the non-static method doesnt exist yet. A static method (by definition) always exists.

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.

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

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 isnt really any reason for it to be an instance method. Its a language design decision to allow it anyway rather than making up an extra rule to forbid it.

Leave a Reply

Your email address will not be published.