Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you force constructor signatures and static methods?

Tags:

Is there a way of forcing a (child) class to have constructors with particular signatures or particular static methods in C# or Java?

You can't obviously use interfaces for this, and I know that it will have a limited usage. One instance in which I do find it useful is when you want to enforce some design guideline, for example:

Exceptions
They should all have the four canonical constructors, but there is no way to enforce it. You have to rely on a tool like FxCop (C# case) to catch these.

Operators
There is no contract that specifies that two classes can be summed (with operator+ in C#)

Is there any design pattern to work around this limitation? What construct could be added to the language to overcome this limitation in future versions of C# or Java?

like image 514
Sklivvz Avatar asked Oct 02 '08 07:10

Sklivvz


People also ask

How are constructors used in static methods?

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced.

How do you make a constructor static?

No, we cannot define a static constructor in Java, If we are trying to define a constructor with the static keyword a compile-time error will occur. In general, static means class level. A constructor will be used to assign initial values for the instance variables.

Can we call constructor from static method?

Static method cannot cannot call non-static methods. Constructors are kind of a method with no return type.

What is the signature of a constructor?

A constructor signature is the constructor name followed by the parameter list which is a list of the types of the parameters and the variable names used to refer to them in the constructor. Overloading is when there is more than one constructor. They must differ in the number, type, or order of parameters.


1 Answers

Using generics you can force a type argument to have a parameterless constructor - but that's about the limit of it.

Other than in generics, it would be tricky to actually use these restrictions even if they existed, but it could sometimes be useful for type parameters/arguments. Allowing static members in interfaces (or possibly static interfaces) could likewise help with the "generic numeric operator" issue.

I wrote about this a little while ago when facing a similar problem.

like image 112
Jon Skeet Avatar answered Oct 11 '22 12:10

Jon Skeet