public class JavaStaticExample {
// 静态变量,属于类,所有对象共享同一份数据
static int count = 0;
// 静态方法,可以直接通过类名调用
public static void incrementCount() {
count++;
}
// 实例方法,需要通过对象调用
public void showCount() {
System.out.println("Current count: " + count);
}
public static void main(String[] args) {
// 调用静态方法,不需要创建对象
JavaStaticExample.incrementCount();
JavaStaticExample.incrementCount();
// 创建对象并调用实例方法
JavaStaticExample example1 = new JavaStaticExample();
example1.showCount(); // 输出: Current count: 2
JavaStaticExample example2 = new JavaStaticExample();
example2.showCount(); // 输出: Current count: 2
}
}
静态变量 (static int count = 0;):
count 是一个静态变量,因此 example1 和 example2 共享同一个 count。静态方法 (public static void incrementCount()):
incrementCount() 是一个静态方法,可以直接通过 JavaStaticExample.incrementCount() 调用。实例方法 (public void showCount()):
showCount() 是一个实例方法,需要通过 example1.showCount() 或 example2.showCount() 调用。main 方法:
main 方法是程序的入口点。main 方法演示了如何调用静态方法和实例方法,并展示了静态变量的行为。上一篇:java 方法引用
下一篇:static java
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站