Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a constructor generic without making the class generic?

Tags:

java

I have seen in Java that one can make a Class generic and a method generic. I have also seen codes that make the constructor generic along with the Class. Can I make only the constructor generic? And if yes, how to call the constructor?

like image 951
Birendra Avatar asked Sep 11 '15 20:09

Birendra


People also ask

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

Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.

Can a constructor be generic?

Constructors can be Generic, despite its class is not Generic.

Can a generic class be a subclass of a non-generic class?

A generic class can extend a non-generic class.

Can we have non-generic method in generic class C#?

We can have generic methods in both generic types, and in non-generic types. Our first example in Program 43.1 is the generic method ReportCompare in the non-generic class StringApp . ReportCompare is a method in the client class of String<T> which we encountered in Section 42.4.


1 Answers

Yes you can.

class Example {

    public <T> Example(T t) {}

    public static void main(String[] args){

        // In this example the type can be inferred, so new Example("foo") 
        // works, but here is the syntax just to show you the general case.
        Example example = new<String>Example("foo");
    }
}
like image 50
Paul Boddington Avatar answered Sep 21 '22 20:09

Paul Boddington