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?
Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.
Constructors can be Generic, despite its class is not Generic.
A generic class can extend a non-generic class.
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.
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");
}
}
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