用 static 修饰变量时应该注意的问题

1.使用 static 修饰的变量由该类的全体对象共享

 1 public class TestStatic {
 2     static int a;
 3     
 4     public void setA(int a) {
 5         this.a = a;
 6     }
 7     
 8     public void printA() {
 9         System.out.println(a);
10     }
11     
12     public static void main(String[] args) {
13         TestStatic t1 = new TestStatic();
14         t1.setA(10);
15         t1.printA();
16         
17         TestStatic t2 = new TestStatic();
18         t2.printA();
19     }
20 }

输出结果 

10
10

t1 中我们把静态变量 a 的值设为了 10,在 t2 中并没有对 a 进行任何操作

我们可以清楚的看到被 static 修饰的变量是被该类的全体对象所共享的

2.在子类中如果没有重新定义继承自父类的静态变量,那么子类和父类共享同一个静态变量

(1)没有在子类重新定义静态变量 a

public class TestStatic2 extends Father{
    public static void main(String[] args) {
        a++;
        System.out.println(a);
    }
}

class Father{
    static int a = 10;
}
11
(2)在子类中重新定义静态变量 a
public class TestStatic2 extends Father{
    static int a = 5;
    public static void main(String[] args) {
        a++;
        System.out.println(a);
    }
}

class Father{
    static int a = 10;
}
6

static 修饰的变量,在子类中如果没有重新定义继承自父类的静态变量,那么子类和父类共享同一个静态变量

猜你喜欢

转载自www.cnblogs.com/cheng1994/p/11001752.html