Java中的静态变量 [英] Static variables in java

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

问题描述

我有这样的情况

public class Test{

   static int a;
   int b;

   public static void main(String[] args){

      Test t1  = new Test();
      Test t2 = new Test();

   }
}

对象t1和对象t2中的变量是什么?

What will be the variables in object t1 and object t2?

根据我的理解,由于变量 a 是静态变量,因此它将同时存在于对象1和对象2中.

As per my understanding since variable a is a static variable it will be both in object 1 and object 2.

b 将为两个对象创建单独的副本.

And b will be created separate copy for both the objects.

但是当我给变量b即( int b = 1 )赋值并像 System.out.println(t1.b)那样调用它时, System.out.println(t2.b)

But when I assign a value to variable b ie(int b=1) and call it like System.out.println(t1.b), System.out.println(t2.b)

这两个对象的输出不是1,而是错误.

Instead of getting an error I am getting 1 as output from both the objects.

那是为什么?

推荐答案

根据我的理解,由于变量a是静态变量,因此它将同时出现在对象1和对象2中.

As per my understanding since variable a is static variable it will be both in object 1 and object 2.

不.它都不在 对象中.它的存在根本不涉及任何特定实例.尽管Java 允许,您还是可以通过引用来引用它,例如 int x = t1.a; 不应这样做.相反,您应该通过类名称(在您的情况下为 test.a 来引用它-尽管您还应该开始遵循Java命名约定)以使其清晰可见.

No. It's not in either object. It exists without reference to any particular instance at all. Although Java allows you to refer to it "via" a reference, e.g. int x = t1.a; you shouldn't do so. You should instead refer to it via the class name (test.a in your case - although you should also start following Java naming conventions) to make it clear that it's static.

然后将为两个对象创建b的单独副本.

And b will be created separate copy for both the objects.

是的

但是当我给变量b即( int b = 1 )赋值并像 System.out.println(t1.b)一样调用它时,System.out.println(t2.b)而不是出错,我从两个对象的输出中得到了1.

But when I assign a value to variable b ie(int b=1) and call it like System.out.println(t1.b), System.out.println(t2.b) Instead of getting an error I am getting 1 as output from both the objects.

那是因为您已经为它赋予了一个初始值,可以为每个新对象分配初始值.那是完全合理的.仍然有两个自变量:

Well that's because you've basically given it an initial value to assign for each new object. That's entirely reasonable. There are still two independent variables:

t1.b = 2;
t2.b = 3;
System.out.println(t1.b); // Prints 2
System.out.println(t2.b); // Prints 3

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

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