0

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.

2
  • 1
    You get an error saying you have multiple errors. Please tell us what they are. Commented Mar 24, 2015 at 2:22
  • 2
    Just to clarify static does not dictate access level, it ensures that the variable belongs to the class itself (and not each instance), and is accessible by the syntax MyClass.myVar. The modifiers public, private, protected, and default (no keyword) are what control visibility. Commented Mar 24, 2015 at 2:48

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.