spotTop
spotTop

Reputation: 87

Constructor of a class

I am having trouble understanding this.

"Lastly, modify WordTransformer and SentenceTransformer so you can not create an instance of the class. Remember, with static methods and variables, you do not need to make an instance of a class. (Hint: a constructor of a class is what allows an instance of that class to be created...new WordTransformer(), what keyword can you add to the definition of that constructor that will prevent the construct from being called anywhere but in the class itself?)"

It says so you can not create an instance of this class, but if you make the class private it becomes an error. Says the only options are public static or final.

Upvotes: 0

Views: 62

Answers (4)

Techuila
Techuila

Reputation: 1287

Private constructor and static methods on a class marked as final.

Upvotes: 0

zmo
zmo

Reputation: 24802

well you shall qualify the constructor as private, not the class. cf this document:

Private constructors prevent a class from being explicitly instantiated by its callers.

here's an example:

public class WordTransformer {
    private WordTransformer() {
    }
}

N.B.: as it sounds a lot like an assignment, I hope that you'll read the linked documentation and understand why and when to use it!

Upvotes: 3

Simon
Simon

Reputation: 6363

private WordTransformer(...) {
    ...
}

Making the constructor private will allow other methods of this class to create instances of the class but no one can create instances from the outside. Example of when this is used in practice is the singleton pattern or builder pattern.

Upvotes: 0

NickL
NickL

Reputation: 4276

Make the constructor private: private WordTransformer(){}

Upvotes: 1

Related Questions