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

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

public class TestStatic {
    static int a;
    
    public void setA(int a) {
        this.a = a;
    }
    
    public void printA() {
        System.out.println(a);
    }
    
    public static void main(String[] args) {
        TestStatic t1 = new TestStatic();
        t1.setA(10);
        t1.printA();
        
        TestStatic t2 = new TestStatic();
        t2.printA();
    }
}

输出结果

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 修饰的变量,在子类中如果没有重新定义继承自父类的静态变量,那么子类和父类共享同一个静态变量

原文地址:https://www.cnblogs.com/syxy/p/10040615.html