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

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

问题描述

这道题的题目实际上是之前的一道试题,我正在寻求澄清/答案.

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

请注意,我正在学习 Java 并且正在熟悉它的语法.

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?

我在正确的轨道上吗?

此外,静态"究竟是做什么的?如果类的实例驻留在类的主实例中,它是否只是静态的?

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?

非常感谢.

推荐答案

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

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.

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

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();

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

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();

t1 和 t2 将共享相同的 x.

Both t1 and t2 will share the same x.

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

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