Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a constructor on a generic class that introduces additional generic types?

Tags:

c#

generics

I'm trying to build a generic class whose constructor introduces an additional type, but the compiler says no-no.

I don't quite understand why the following doesn't work:

public class Foo<T>
{
    public Foo<T,TBar>(TBar tBar)
    {
    ...
    }
}

It's not critical as I can write the class using a fluent api (which might be preferred), but I'd still like to understand why I can't. The only explanation I can think of is that the compiler doesn't like method-level generic type declaration mixed with class-level generic type declaration.

like image 724
BlackjacketMack Avatar asked Nov 16 '13 21:11

BlackjacketMack


People also ask

Can we use generic constructors in non generic classes?

Generic constructors Constructors are similar to methods and just like generic methods we can also have generic constructors in Java though the class is non-generic. Since the method does not have return type for generic constructors the type parameter should be placed after the public keyword and before its (class) name.

How do you invoke a generic constructor with a parameter?

Since the method does not have return type for generic constructors the type parameter should be placed after the public keyword and before its (class) name. Once you define a generic constructor you can invoke (instantiate the class using that particular constructor) it by passing any type (object) as parameter.

What is a generic class in Java?

In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype.

Is the entry class a generic class?

Although the Entry class isn't generic, it has a generic constructor, as it has a parameter element of type E. The generic type E is bounded and should implement both Rankable and Serializable interfaces.


1 Answers

It is not possible. The constructor is not called like a method, it is invoked by specifying the class name only (after the new keyword). Normal methods, on the other hand, can have additional generic type arguments.

like image 144
fejesjoco Avatar answered Oct 05 '22 23:10

fejesjoco