初学者最常犯的错误是试图“静态”地使用类属性而不创建该类的实例。它会给你留下上面提到的错误信息:

您可以将非静态方法设置为静态,也可以创建该类的实例来使用它的属性。

背后的原因是什么?我关心的不是解决方法,而是原因。

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

当前回答

静态方法将操作关联到对象类型,而非静态方法将操作关联到该类型对象的实例。通常,它是一个与实例相关的方法。

Ex:

Car类可能有一个wash方法,用于指示清洗特定的汽车,而静态方法应用于Car类型。

其他回答

你不能给不存在的东西打电话。因为还没有创建对象,所以非静态方法还不存在。静态方法(根据定义)总是存在的。

我刚刚意识到,我认为人们不应该过早地接触“静态”的概念。

静态方法应该是例外,而不是规范。尤其是在你想学习OOP的时候。(为什么要从规则的例外开始呢?)这与Java的教学方法截然相反,你应该学习的“第一件”事情是公共静态空的主要内容。(很少有真正的Java应用程序有自己的主方法。)

所以你问的是一个非常核心的原因?

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

对不起我的英语!我是拉丁!

静态方法将操作关联到对象类型,而非静态方法将操作关联到该类型对象的实例。通常,它是一个与实例相关的方法。

Ex:

Car类可能有一个wash方法,用于指示清洗特定的汽车,而静态方法应用于Car类型。

这背后的简单原因是父类的静态数据成员 可以访问(仅当它们未被覆盖时),但例如(非静态) 数据成员或方法需要它们的引用,因此它们只能是 通过对象调用。