Is there a way to prevent the usage of the default constructor?
All I can think of is throwing an exception, but I would like something that causes a compile time error.
The drawback of a default constructor is that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class to different values. The default constructor initializes: All numeric fields in the class to zero. All string and object fields to null.
The compiler doesn't ever enforce the existence of a default constructor. You can have any kind of constructor as you wish. For some libraries or frameworks it might be necessary for a class to have a default constructor, but that is not enforced by the compiler.
This default constructor supplied by Java as above calls the super class's no-arg constructor. If it can't find one, then it will throw an error.
There are a few reasons to delete the default constructor. The class is purely static, and you don't want users instantiating a class with only static methods/members. An example of such a class might be one that implements the factory design pattern using only static methods to create new classes.
I think that should cover all bases...
Make it private.
So,
class SomeClass { private SomeClass() { } public SomeClass(int SomeParam) { } }
You can just make it private:
private MyClass()
{
}
Alternatively (if you didn't know already) if you just declare a constructor with parameters, the default one isn't added by the compiler, e.g.
private MyClass(string myParameter)
{
//Can't call new MyClass() anymore
}
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