Java基础--- static关键字
静态成员 — Static Fields
- 一个类只有这一个这样的成员实例, 直接用类名调用
- 即使没有对象实例, 静态成员也存在
Example: 给每个雇员产生unique ID
public void setId() {
id = nextId;
nextId++;
}
harry.id = Employee.nextId;
Employee.nextId++;
静态常量 — Static Constant
- 和静态成员一样, 只不过是常量
public class Math {
. . .
public static final double PI = 3.14159265358979323846;
. . .
}
Math.PI.
Another static constant that you have used many times is System.out. It is declared in the System class as follows:
public class System {
. . .
public static final PrintStream out = . . .;
. . .
}
- it is never a good idea to have public fields, because everyone can modify them.
- However, public constants (that is, final fields) are fine. Since out has been declared as final, you cannot reassign another print stream to it:
System.out = new PrintStream(. . .); // Error--out is final
静态方法 — Static Methods
- 静态方法跟类的对象没有关系, 不管有没有对象实例, 静态方法都存在. 也是直接用类名调用
- 静态方法不能使用非静态成员变量, 但是可以使用静态成员变量
什么时候使用静态方法:
- 当一个方法不需要使用对象的状态, 也就是所需的参数都是外部直接传入的, 比如:
Math.pow
- 当一个方法使用的都是静态成员变量时
静态类 — Static Class
- 只有内部类可以是静态的, 也只有内部类可以用static关键字修饰
- 静态内部类是不需要依赖于外部类的,这点和类的静态成员属性有点类似
- 它不能使用外部类的非static成员变量或者方法
- 因为在没有外部类的对象的情况下,可以创建静态内部类的对象,如果允许访问外部类的非static成员就会产生矛盾,因为外部类的非static成员必须依附于具体的对象
- 下面代码中, 如果TaskOne和TaskTwo不用static修饰, 则不能直接在main中创建对应的实例
- 因为TaskOne和TaskTwo都为内部类, 而内部类是依赖于外部类(只有先创建外部类实例才能创建内部类实例)
- 所以将TaskOne和TaskTwo变为静态内部类,则可以直接现在main中创建对应实例, 因为静态内部类是不需要依赖于外部类的
package SimpleThread;
public class SimpleRunnable {
public static class TaskOne implements Runnable{
static int count = 0;
@Override
public void run() {
while(true) {
count++;
System.out.println("taskOne: " + count);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static class TaskTwo implements Runnable{
static int count = 0;
@Override
public void run() {
while(true) {
count++;
System.out.println("taskTwo: " + count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
//TaskOne和TaskTwo变为静态内部类,则可以直接现在main中创建对应实例, 因为静态内部类是不需要依赖于外部类的
TaskOne taskOne = new TaskOne();
TaskTwo taskTwo = new TaskTwo();
Thread t1 = new Thread(taskOne);
Thread t2 = new Thread(taskTwo);
t1.start();
t2.start();
}
}