Java 类设计:静态关键字与类特性解析
1. 静态关键字的使用
在 Java 中,静态关键字( static
)有着重要的用途。我们先来看一个简单的例子,尝试编写一个类来统计该类创建的对象数量。
// Counter class should count the number of instances created from that class
public class Counter {
private int count; // variable to store the number of objects created
// for every Counter object created, the default constructor will be called;
// so, update the counter value inside the default constructor
public Counter() {
count++;
}
public void printCount() { // method to print the counter value so far
System.out.println("Number of instances created so far is: " + count);
}
public static void main(String []args) {
Counter anInstance = new Counter();