saltyeggs
saltyeggs

Reputation: 93

Is it okay to not use a constructor in a class?

I have a class, which has some private static final fields (unsure if it is correct to call these constants), and one other instance variable set just private, which is direct copy of one of the private static final fields.

Every time the object is created from other classes, I want it to have the same variables, as they are assigned in the class, and without creating a constructor, Java allows me access all of the methods with the correct returns as I would expect.

Is it okay to not create a constructor in this case?

Upvotes: 0

Views: 447

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075855

There are at least two answers to your question:

  1. It's fine not to include a constructor in your class. The Java compiler will add a default zero-parameters constructor for you.

  2. It sounds like you shouldn't be constructing instances of your class in the first place. :-)

You've said

Every time the object is created from other classes, I want it to have the same variables, as they are assigned in the class, and without creating a constructor, Java allows me access all of the methods with the correct returns as I would expect.

It sounds like you have roughly:

class TheClass {
    public final SomeType variable = /*...*/;
    // ...
}

...and you're doing this:

TheClass instance = new TheClass();
doSomethingWith(instance.variable);

There's no reason to create an instance there, just use the class name directly:

doSomethingWith(TheClass.variable);

Java is somewhat interesting in that it allows you to access static members via instance references (instance.variable), but the normal way to access them is through the class (TheClass.variable).

Also, if your static members aren't final, you can get some very confusing-seeming behavior:

TheClass a = new TheClass();
a.variable = 1;
TheClass b = new TheClass();
b.variable = 2;
System.out.println(a.variable); // 2?!?!?!

So in general, best to avoid accessing static members via instance references.

Alternately, make the class a singleton with instance (non-static) members instead.

Upvotes: 1

Related Questions