public class Stuff {
public static String name = "I'm a static variable";
}
public class Application {
public static void main(String[] args) {
System.out.println(Stuff.name);
}
}
1.用你静态变量声明常量(在以后过不希望改变的值),用到**final**
public class Stuff {
public final static String NAME = "I'm a static variable";
}
public class Application {
public static void main(String[] args) {
System.out.println(Stuff.NAME);
}
}
2.用静态变量来记录对象(在一个对象里有多少对象被创建了)
首先来回顾一下构造函数:
1. 构造函数名和类名相同
2. 应该声明为public,使外部类可以访问到它
public class Stuff {
public Stuff() {
System.out.println("Stuff object constructed!");
}
}
public class Application {
public static void main(String[] args) {
Stuff stuff1 = new Stuff();
Stuff stuff2 = new Stuff();
Stuff stuff3 = new Stuff();
}
}
构造函数将被自动调用三次
public class Stuff {
// Set count to zero initially.
static int count = 0;
public Stuff() {
// Every time the constructor runs, increment count.
count = count + 1;
// Display count.
System.out.println("Created object number: " + count);
}
}
1. 给对象加ID
public class Stuff {
// Set count to zero initially.
static int count = 0;
// Use this to store an ID for each object.
int id;
public Stuff() {
// Every time the constructor runs, increment count.
count = count + 1;
// Set the object ID using count.
id = count;
// Now count can change but id will be unaffected.
}
// This just returns the ID.
public int getId() {
return id;
}
}
public class Application {
public static void main(String[] args) {
Stuff stuff1 = new Stuff();
Stuff stuff2 = new Stuff();
Stuff stuff3 = new Stuff();
System.out.println("ID of object 2 is: " + stuff2.getId());
}
结果:ID of object 2 is: 2
静态函数不需要实例化
java的Math class的所有成员都是静态的。