This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: Why can’t static methods call non-static members?

The most common mistake beginners make is trying to use a class property “statically” without creating an instance of the class. It will report the following error:

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

Why is that? I’m not looking for a solution. I’d love to know what’s behind it. The core reason!

private java.util.List<String> someMethod(a){
    /* 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();         
}
Copy the code

Answer a

You can’t call something that doesn’t exist. Because no object has been created, non-static methods do not yet exist. Static methods (by definition) always exist.

Answer two

The essence of object-oriented programming is to encapsulate logic with the data it operates on.

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

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

    public static void main(String[] args){ System.out.println( getFoo() ); }}Copy the code

What are the likely results of running the above program?

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

In theory, instance methods that don’t access any instance data can work in a static context, but there’s really no reason to treat them as instance methods.

The article translated from Stack Overflow:stackoverflow.com/questions/2…