我知道如果我有同一个类的多个实例,它们将共享相同的类变量,因此无论我有多少个类实例,类的静态属性都将使用固定数量的内存.
我的问题是:
如果我有一些子类从它们的超类继承一些静态字段,它们是否会共享类变量?
如果没有,确保它们共享相同类变量的最佳实践/模式是什么?
解决方法
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 } }
原文地址:https://www.jb51.cc/java/127417.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。