ottercoder
ottercoder

Reputation: 862

Use of constants in Java class

I have a Request class with a number of final and not final fields.

It's used for one and only one type of request. But the service, to which it is sent, requires a code to distinguish the type of operation. I'm created a constant which will be initialized every time with the Request class. For example:

public class Request {

  @JsonProperty("const")
  private static final String CONSTANT = "field"

  @JsonProperty("data")
  private int data;

  public String getConstant() {
      return CONSTANT;
  }

  public int getData() {
      return this.data;
  }
}

I thought about initializing it inside the constructor or explicitly using the operation code as the parameter to the constructor, despite the fact that it will never change. Should it be static final?

The question is, what is the best practice in this case?

Upvotes: 2

Views: 302

Answers (2)

Yogi
Yogi

Reputation: 1895

For such fields, I would prefer using Enum constants and initialize Constant field via Constructor/Builder pattern. Provide only Getter method for such CONSTANT field.

Upvotes: 0

Chinmay jain
Chinmay jain

Reputation: 999

Static and final are two completely different things:

static should be used for things that are shared across all instances (objects) of a certain type (class)

Declaring the field as final will ensure that the field is a constant and cannot change.

In your case, there is no problem in sharing the variable across all instances, so declaring it as static final won't be a problem according to best practices.

Upvotes: 2

Related Questions