我知道如果我有同一个类的多个实例,它们将共享相同的类变量,因此无论我有多少个类实例,类的静态属性都将使用固定数量的内存.
我的问题是:
如果我有一些子类从它们的超类继承一些静态字段,它们是否会共享类变量?
如果没有,确保它们共享相同类变量的最佳实践/模式是什么?
解决方法
If I have a couple subclasses inheriting some static field from their
superclass,will they share the class variables or not?
是的,它们将在单个Classloader中在当前运行的Application中共享相同的类变量.例如,考虑下面给出的代码,这将为您提供每个子类共享类变量的公平概念.
- class Super
- {
- static int i = 90;
- public static void setI(int in)
- {
- i = in;
- }
- public static int getI()
- {
- return i;
- }
- }
- class Child1 extends Super{}
- class Child2 extends Super{}
- public class ChildTest
- {
- public static void main(String st[])
- {
- System.out.println(Child1.getI());
- System.out.println(Child2.getI());
- Super.setI(189);//value of i is changed in super class
- System.out.println(Child1.getI());//same change is reflected for Child1 i.e 189
- System.out.println(Child2.getI());//same change is reflected for Child2 i.e 189
- }
- }