I am developing a library and I don’t want the user to create an instance of a class directly with the new keyword, instead I have special methods to create objects. So is it possible if the user instantiates a class using the new keyword, that the compiler gives error.
For Example:
public class MyClass {
private MyClass(int i) { }
public MyClass createMyClassInt(int i) {
return new MyClass(i);
}
private MyClass(double d) { }
public MyClass createMyClassDouble(double d) {
return new MyClass(d);
}
}
So when the user tries to instantiate MyClass myClass = new MyClass();, the compiler will give an error.
Your code is nearly fine – all you need is to make your
createmethods static, and give them a return type:The methods have to be static so that the caller doesn’t already have to have a reference to an instance in order to create a new instance 🙂
EDIT: As noted in comments, it’s probably also worth making the class
final.