user287474
user287474

Reputation: 325

Accessing a public final constant in another class?

I'm trying to access a constant in java that's stored in "Constants.java", a private class, and use it in another to evaluate it in a method.

I'm not allowed to change the Constants class, and the constant I'm trying to accessed is initialized in the following way:

 public final int INVENTORY_MAX = 100;

I tried the following:

 if (h <= Constants.INVENTORY_MAX)

But Constants is private and without it, it's asking me to make a local variable. I also would make the variable static, but the code is given by the professor and I cannot change it in any way. Please help!

Thank you.

EDIT: The following is a screenshot that shows that the Constants class is private. Ignore the error message under Constants.

Class Constructor

Constants

Upvotes: 1

Views: 7089

Answers (2)

YoungHobbit
YoungHobbit

Reputation: 13402

EDIT: It does not say class is private, it is saying constructor is private. Which means you cannot create an instance of the class outside of it.

So you do the following:

Constants consts = Constants.getInstance();
if (h <= consts.INVENTORY_MAX)

Upvotes: 5

Elliott Frisch
Elliott Frisch

Reputation: 201439

I would, but the Constants class if given by my professor that is not allowing >me to change the Constants class.

There is also this method in his code that may be useful:

public static Constants getInstance() {
     if(instance == null)
         instance = new Constants();
     return instance;
}

Per your edit Constants is a Singleton, so first get the instance and then access the field directly.

INVENTORY_MAX = 100;
Constants consts = Constants.getInstance(); // new Constants();
// ...
if (h <= consts.INVENTORY_MAX)

Upvotes: 3

Related Questions