Java中的实例和类(静态)变量之间有什么区别 [英] What is the difference between an instance and a class (static) variable in Java

查看:153
本文介绍了Java中的实例和类(静态)变量之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的标题实际上是以前的考试问题,我正在寻找澄清/答案。



请注意我正在学习Java和我熟悉它的语法。



我知道之前可能已经问过这个问题,如果有的话,有人可以告诉我在哪里可以访问这个问题吗?如果是这种情况,请接受我的道歉。
为了表明我一直在研究这个领域,我自己的理解是实例变量属于某个类(模板)的对象/实例,并且可以在需要时在该实例/对象中进行更改(变异) 。



类变量是一个只有一个副本且可以被访问但不被修改(变异?)的变量,但是根据需要可用于所有类? / p>

我是否在正确的轨道上?



此外,'静态'到底是做什么的?如果一个类的实例位于类的主实例中,那么它是否只是静态的?



非常感谢。

解决方案

静态变量由所有人共享类的实例,而实例变量对于类的每个实例都是唯一的。



静态变量的内存在编译时分配,它们在加载时加载,在类初始化时初始化。在实例变量的情况下,以上所有操作都是在运行时完成的。



这是一个有用的例子:



一个实例变量是每个对象一个:每个对象都有自己的实例变量副本。

  public class Test {

int x = 5;

}

测试t1 = new Test();
测试t2 =新测试();

t1和t2都有自己的x副本。



静态变量是每个类一个:该类的每个对象共享相同的静态变量。

  public class Test {

public static int x = 5;

}

测试t1 = new Test();
测试t2 =新测试();

t1和t2都将共享相同的x。


The title of this question is actually a previous examination question and I am looking for clarification / an answer to it.

Please note that I am learning Java and am becoming familiar with its syntax.

I understand that this question may have been asked before and if so can someone please show me where I may access the question if possible? Also please accept my apologies if this is the case. To show that I have been researching this area, my own understanding is that instance variables belong to the objects / instances of a certain class (template) and can be changed (mutated) within that instance / object as and when required.

A class variable is a variable that has only one copy and can be accessed but not be modified (mutated?), but is available to all classes as required?

Am I on the right track here?

Also, what exactly does the 'static' do? Is an instance of a class only static if it resides within the main instance of a class?

Many thanks.

解决方案

A static variable is shared by all instances of the class, while an instance variable is unique to each instance of the class.

A static variable's memory is allocated at compile time, they are loaded at load time and initialized at class initialization time. In the case of an instance variable all of the above is done at run time.

Here's a helpful example:

An instance variable is one per object: every object has its own copy of its instance variable.

public class Test{

   int x = 5;

 }

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

Both t1 and t2 will have their own copy of x.

A static variable is one per class: every object of that class shares the same static variable.

public class Test{

   public static int x = 5;

 }

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

Both t1 and t2 will share the same x.

这篇关于Java中的实例和类(静态)变量之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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