Skip to content
Advertisement

Best way to access variables from another class?

I need to access variables from another class and I have done it using 2 different approaches described below.

My question is which of the two is preferable and why since both work quite nicely -or is there another better way to do it?. I have also done it using internal classes but this is inconvenient when the number of code lines gets growing ever larger.

In the following test code the commented asterisks repesent different files:

JavaScript

Now as you can see below UpperPanel must access JButtons from LowerPanel and LowerPanel must access the menu from UpperPanel. For this reason I could pass pUp as a parameter to the LowerPanel constructor but I can’t pass pLow as parameter to UpperPanel as it hasn’t been created yet.

Therefore I have used 2 methods, one declaring instances of the relevant classes and the other using static variables. The previous 2 classes above are the same in each approach.

Below is the code of the panels in the first case:

JavaScript

And these are the panels in the second case:

JavaScript

Advertisement

Answer

In general there are 2 ways to access a variable from another class:

  1. You create an object of that class. Then this object has all the variables from the scope of that class assigned to it. For example:
JavaScript
  1. You can also create a static variable. Then the variable is assigned to the class not the object of that class. This way you will not need to create an object, but all instances of the class will share the same variable.
JavaScript

If you do not want to create a new instance of a class every time, and always use the same instance, you can create a singleton object. You write a getter method that gets you the object. It looks like this:

JavaScript

I see you work with a JFrame. Then you will probably want to make it a singleton. Else you will open a new instance of the JFrame every time you call upon it, which is not recommended. Does this answer your question?

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement