Java静态变量和继承以及内存 [英] Java Static Variables and inheritance and Memory

查看:113
本文介绍了Java静态变量和继承以及内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果我有同一个类的多个实例,他们都会共享相同的类变量,所以该类的静态属性将使用固定的内存量,无论我有多少个类的实例。



我的问题是:
如果我有一个子类从他们的父类继承一些静态字段,他们会共享类变量还是不?



如果没有,最好的做法/模式是什么,以确保它们共享相同的类变量?

超类的一些静态字段,它们将共享类变量或类变量。不是?


是在单个Classloader中,在当前运行的应用程序中共享相同的类变量。
示例考虑下面给出的代码,这将让你公平地了解其每个子类共享类变量。

  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); //在超类中更改i的值
System.out.println(Child1.getI()); //对Child1反映相同的更改,即189
System.out.println(Child2.getI()); //对于Child2反映相同的变化ie 189
}
}


I know that if I have multiple instance of the same class all of them are gonna share the same class variables, so the static properties of the class will use a fixed amount of memory no matter how many instance of the class I have.

My question is: If I have a couple subclasses inheriting some static field from their superclass, will they share the class variables or not?

And if not, what is the best practice/pattern to make sure they share the same class variables?

解决方案

If I have a couple subclasses inheriting some static field from their superclass, will they share the class variables or not?

Yes They will share the same class variables throughout the current running Application in single Classloader.
For example consider the code given below, this will give you fair idea of the sharing of class variable by each of its subclasses..

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
    }
}

这篇关于Java静态变量和继承以及内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆