在Java中,static关键字可以用来修饰类、方法和变量。
示例:
public static class MyClass {
public static int staticVariable = 10;
public static void staticMethod() {
// 静态方法的实现
}
}
// 访问静态成员
int variable = MyClass.staticVariable;
MyClass.staticMethod();
示例:
public class MyClass {
public static void staticMethod() {
// 静态方法的实现
}
}
// 调用静态方法
MyClass.staticMethod();
示例:
public class MyClass {
public static int staticVariable = 10;
}
// 访问静态变量
int variable = MyClass.staticVariable;
需要注意的是,静态方法只能访问静态成员,而不能访问非静态成员;静态方法中不能使用this关键字,因为this表示当前对象的引用,而静态方法没有对象实例。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:java static关键字怎么使用