Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access Variable from Another Class without Creating New Object

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

like image 809
htmlhigh5 Avatar asked Dec 01 '22 16:12

htmlhigh5


1 Answers

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();
like image 93
Christian Tapia Avatar answered Dec 10 '22 15:12

Christian Tapia