简体   繁体   中英

Using a global (static) variable in Java

I have a need to share a variable between two classes in the same package. I would not like to debate the "why" I'm using a global variable. I avoid them normally at all cost.

My understanding is that I need to declare my variable as static, and that any variable declared in such a manner is available to all classes in the package. I am using a Java library called Lanterna that is used to create text-based GUIs. In order write characters to the screen buffer, I have to create an object (which I called screen) of the Screen type. The two declarations below are placed near the top of my entry class (not in the constructor).

public static Terminal terminal = TerminalFacade.createTerminal(System.in, System.out, Charset.forName("UTF8"));

public static Screen screen = new Screen(terminal);

The types Terminal and Screen are declared as import statements at the top of my program. I don't receive any errors in Eclipse with these statement. In the class where I attempt to access the screen object, I get an error saying Multiple Markers at this line, screen cannot be resolved.

If any additional information needs to be provided please let me know.

While terminal and screen are in-scope everywhere, they are not automatically imported, and you have to reference them by the class that contains them.

For example, if you declared them in class Myclass , you would access them by eg.

MyClass.terminal.frobnicate();

Alternatively, though this is not standard practice in most cases, you can import them like so:

import static myPackage.MyClass.terminal; 

Then you will be able to simply reference terminal without clarifying that you refer to MyClass 's terminal , and not some other class's static field called terminal .

Instead of import you need a static import (The Static Import Java guide says, in part, The static import construct allows unqualified access to static members without inheriting from the type containing the static members ). Something like (obviously with your entry-class)

import static com.foo.EntryClass.terminal;
import static com.foo.EntryClass.screen;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM