Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is generic constructor in non-generic class supported?

Is it not supported, is it supported but I have to do some tricks?

Example:

class Foo {   public Foo<T1,T2>(Func<T1,T2> f1,Func<T2,T1> f2)   {      ...   } } 

the generics are only used in constructor, there is no field/property depended on them, I use it (generics) to enforce the type correlation for f1 and f2.

Remark: I found the workaround -- static method Create, but anyway I am curious why I have problem with straightforward approach.

like image 920
greenoldman Avatar asked Aug 31 '10 07:08

greenoldman


People also ask

Can you have a generic method in a non-generic class?

Yes, you can define a generic method in a non-generic class in Java.

Can you have generic constructors in Java Though the class is generic?

Constructors are similar to methods and just like generic methods we can also have generic constructors in Java though the class is non-generic.

Can a non-generic class inherit a generic class?

Yes you can do it.

Can a generic class have constructor?

A generic constructor is a constructor that has at least one parameter of a generic type. We'll see that generic constructors don't have to be in a generic class, and not all constructors in a generic class have to be generic.


2 Answers

No, generic constructors aren't supported in either generic or non-generic classes. Likewise generic events, properties and finalizers aren't supported.

Just occasionally I agree it would be handy - but the syntax would look pretty awful. For example, suppose you had:

public class Foo<T> {}  public class Foo {     public Foo<T>() {} } 

What would

new Foo<string>() 

do? Call the generic constructor of the non-generic class, or the normal constructor of the generic class? You'd have to differentiate between them somehow, and it would be messy :(

Likewise, consider a generic constructor in a generic class:

public class Foo<TClass> {     public Foo<TConstructor>() {} } 

How would you call the constructor? Hopefully we can all agree that:

new Foo<string><int>() 

is pretty hideous...

So yes, semantically it would be occasionally useful - but the resulting ugliness counterbalances that, unfortunately.

like image 118
Jon Skeet Avatar answered Sep 19 '22 03:09

Jon Skeet


Generic constructors are not supported, but you can get around this by simply defining a generic, static method that returns a new Foo:

class Foo {   public static Foo CreateFromFuncs<T1,T2>(Func<T1,T2> f1,Func<T2,T1> f2)   {      ...   } } 

which is used like this:

// create generic dependencies var func1 = new Func<byte, string>(...); var func2 = new Func<string, byte>(...);  // create nongeneric Foo from dependencies Foo myFoo = Foo.CreateFromFuncs<byte, string>(func1, func2); 
like image 45
Peter Alexander Avatar answered Sep 19 '22 03:09

Peter Alexander