In Java, the static keyword is used to create class-level variables and methods.
When a variable or method is declared as static, it means that it belongs to the class itself, rather than to any particular instance of the class. This means that there is only one copy of the variable or method, regardless of how many instances of the class are created.
To declare a variable or method as static, simply include the keyword before the variable or method declaration. For example:
public class MyClass {
static int myStaticVariable = 42;
static void myStaticMethod() {
System.out.println("Hello, world!");
}
}
In this example, myStaticVariable and myStaticMethod are both declared as static. This means that they can be accessed using the class name, rather than an instance of the class:
int x = MyClass.myStaticVariable;
MyClass.myStaticMethod();
Note that static variables and methods cannot access non-static variables or methods directly. If you need to access a non-static variable or method from a static context, you will need to create an instance of the class first.
来自 Cursor 的解答,讲得非常明白了。
公元2023,AI 元年。
网友评论