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

 

相关文章:

  • 2022-12-23
  • 2021-09-12
  • 2022-01-04
  • 2021-07-19
  • 2022-02-09
  • 2022-12-23
  • 2022-12-23
  • 2021-10-22
猜你喜欢
  • 2022-12-23
  • 2021-09-25
  • 2021-12-03
  • 2021-08-30
  • 2021-10-16
  • 2021-11-26
  • 2021-08-04
相关资源
相似解决方案