初学者最常犯的错误是试图“静态”地使用类属性而不创建该类的实例。它会给你留下上面提到的错误信息:
您可以将非静态方法设置为静态,也可以创建该类的实例来使用它的属性。
背后的原因是什么?我关心的不是解决方法,而是原因。
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();
}
到目前为止,答案描述了原因,但还有一件事你可能需要考虑:
你可以通过将方法调用附加到可实例化类的构造函数来调用方法,
Object instance = new Constuctor().methodCall();
or
primitive name = new Constuctor().methodCall();
如果您只希望在单个作用域内使用一次可实例化类的方法,这是非常有用的。如果在一个作用域中从一个可实例化类调用多个方法,一定要创建一个可引用的实例。
所以你问的是一个非常核心的原因?
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).
对不起我的英语!我是拉丁!
面向对象编程的本质是将逻辑与它所操作的数据封装在一起。
实例方法是逻辑,实例字段是数据。它们一起构成了一个物体。
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() );
}
}
运行上述程序可能会得到什么结果?
没有对象,就没有实例数据,虽然实例方法作为类定义的一部分存在,但它们需要对象实例为它们提供数据。
理论上,不访问任何实例数据的实例方法可以在静态上下文中工作,但实际上没有任何理由将其作为实例方法。这是一种语言设计决定,无论如何都要允许它,而不是制定一个额外的规则来禁止它。
到目前为止,答案描述了原因,但还有一件事你可能需要考虑:
你可以通过将方法调用附加到可实例化类的构造函数来调用方法,
Object instance = new Constuctor().methodCall();
or
primitive name = new Constuctor().methodCall();
如果您只希望在单个作用域内使用一次可实例化类的方法,这是非常有用的。如果在一个作用域中从一个可实例化类调用多个方法,一定要创建一个可引用的实例。