我一直在寻找明确的答案,我认为我有点得到它,但同时我不太明白该关键字的概念,静态.
这是我做的场景:
package oops;
public class Math {
boolean notNumber = false;
static boolean notString = false;
public static void main(String[] args) {
int num1 = 1;
static int num2 = 1; //doesn't work
Math math = new Math();
math.notNumber = true;
notNumber = true; //doesn't work
notString = true;
}
public void whatever() {
notNumber = true;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不能在静态方法(或任何方法)中将变量声明为静态?"范围"是什么意思?我知道静态变量与类的特定实例无关,它更像是一个"全局"变量.但是为什么不能在方法(num2)中创建静态变量,但可以使用静态变量(notString)?
当你制作静态变量时,你是否必须在课堂上制作它们?方法不可能?
由于我将notNumber声明为非静态,我知道我必须创建一个对象来访问该变量.但是为什么它在没有任何对象创建的情况下工作,而不是在静态方法main()中?
但是为什么不能在方法内部创建静态变量(num2),但可以使用静态变量(notString)呢?
当你创建静态变量时,你必须在类中创建它们吗?在方法中不可能吗?
static作用域为类上下文。因此static在方法作用域中声明变量是没有意义的。
这就像您在方法中声明了实例字段一样。
声明变量和使用它是两个不同的事情,不遵守相同的规则。
根据经验,您可以在适合该修饰符的位置声明具有特定修饰符的变量。例如 :
并且您可以在与此修饰符兼容的任何上下文中使用具有特定修饰符的变量:
由于我将 notNumber 声明为非静态,我知道我必须创建一个对象来访问该变量。但为什么在不创建任何对象的whatever()中可以工作,而在静态方法main()中却不行呢?
这是一个实例方法:
public void whatever() {
notNumber = true;
}
Run Code Online (Sandbox Code Playgroud)
所以访问类的实例成员是有效的。
而这其他的是一种static方法。因此它可以引用static字段但不能引用实例字段:
public class Math {
boolean notNumber = false; // instance
static boolean notString = false; // static
public static void main(String[] args) {
...
notNumber = true; //doesn't work as refers an instance field
notString = true; // work as refers a static field
}
...
}
Run Code Online (Sandbox Code Playgroud)