Java 如何在不创建新对象的情况下从另一个类访问变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22626695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:56:20  来源:igfitidea点击:

How to Access Variable from Another Class without Creating New Object

javaclassvariables

提问by htmlhigh5

My overly long title says it all... I want to be able to access a variable from another class without creating a new object.

我过长的标题说明了一切...我希望能够在不创建新对象的情况下访问另一个类的变量。

Currently the only way I know how to access another class's variable is:

目前我知道如何访问另一个类的变量的唯一方法是:

Control control = new Control;

int dirtCount = control.dirtCount;

However, if I want to access this variable in my dirt object, I would have to create a new Control object for each one. This creates an endless cycle...

但是,如果我想在我的污垢对象中访问这个变量,我必须为每个对象创建一个新的 Control 对象。这就造成了一个无休止的循环……

how can I access the variable without creating a new object?

如何在不创建新对象的情况下访问变量?

(If you want to see the rest of my code, I can post it. I think that this part is the most relevant though :))

(如果您想查看我的其余代码,我可以发布它。我认为这部分是最相关的 :))

采纳答案by Christian

One way would be declaring that variable as static, which means that it's a class variable(it's different than an instance variable). From Java Tutorial(emphasis mine):

一种方法是将该变量声明为static,这意味着它是一个类变量(它与实例变量不同)。从Java 教程(强调我的):

They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

它们与类相关联,而不是与任何对象相关联。类的每个实例共享一个类变量,该变量位于内存中的一个固定位置。任何对象都可以更改类变量的值,但也可以在不创建类的实例的情况下操作类变量

In the Controlclass:

Control课堂上:

public class Control {
    public static int dirCount;
    // ...
}

and you can use it without creating an instance:

您可以在不创建实例的情况下使用它:

int dirCount = Control.dirCount;

Note:

笔记:

If you want that variable to be privateyou can define a staticgetter method:

如果你想要那个变量,private你可以定义一个staticgetter 方法:

public static int getDirCount() {
    return dirCount;
}

and you can call that method with

你可以用

int dirCount = Control.getDirCount();

回答by imarban

回答by Shekhar Khairnar

In java a class can have two type of member variables

在java中一个类可以有两种类型的成员变量

1) instance variables - they are created with every object of that class, and can be access by object of that class.

1) 实例变量——它们是用那个类的每个对象创建的,并且可以被那个类的对象访问。

2) class variables - they are belongs to class means each and every object can share same variable and can be access by class name

2)类变量 - 它们属于类意味着每个对象都可以共享相同的变量并且可以通过类名访问

Member variables in java

java中的成员变量