如何在不创建新对象的情况下从另一个类访问变量 [英] How to Access Variable from Another Class without Creating New Object

查看:83
本文介绍了如何在不创建新对象的情况下从另一个类访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

但是,如果要在我的dirty对象中访问此变量,则必须创建一个新的每个控件对象。这会创建一个无休止的循环...

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

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

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 :))

推荐答案

一种方法是将该变量声明为 static ,这意味着它是一个类变量(不同于实例变量)。来自 Java教程(重点是我的):

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):


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

Control 类中:

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

,您无需创建即可使用它实例:

and you can use it without creating an instance:

int dirCount = Control.dirCount;

注意:

如果希望该变量为 private ,则可以定义 static getter方法:

If you want that variable to be private you can define a static getter method:

public static int getDirCount() {
    return dirCount;
}

,您可以使用

int dirCount = Control.getDirCount();

这篇关于如何在不创建新对象的情况下从另一个类访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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