What is the reason behind “non-static method canno

2019-09-06 14:13发布

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

标签: java static
13条回答
地球回转人心会变
2楼-- · 2019-09-06 14:55

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"

查看更多
登录 后发表回答