How to Access Variable from Another Class without

2020-06-25 04:09发布

问题:

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

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

回答1:

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

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 Control class:

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 private you can define a static getter method:

public static int getDirCount() {
    return dirCount;
}

and you can call that method with

int dirCount = Control.getDirCount();


回答2:

In java a class can have two type of member variables

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

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



回答3:

Yes, you must read a little bit static variables. You can check it at http://www.caveofprogramming.com/frontpage/articles/java/java-for-beginners-static-variables-what-are-they/