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 create
methods static, and give them a return type:
public static MyClass createMyClassInt(int i) {
return new MyClass(i);
}
public static MyClass createMyClassDouble(double d) {
return new MyClass(d);
}
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
.
if you want to create your class by special method why dont use factory design pattern? static method inside your class which returns you new instance of class
if you just dont want to create new class by default constructor, and you want to force user to use one with parameter, then just don't implement default constructor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With