As everyone knows you can have a generic class in Java by using type arguments:
class Foo<T> { T tee; Foo(T tee) { this.tee = tee; } }
But you can also have generic constructors, meaning constructors that explicitly receive their own generic type arguments, for example:
class Bar { <U> Bar(U you) { // Why!? } }
I'm struggling to understand the use case. What does this feature let me do?
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.
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.
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method.
Generic programming is about abstracting and classifying algorithms and data structures. It gets its inspiration from Knuth and not from type theory. Its goal is the incremental construction of systematic catalogs of useful, efficient and abstract algorithms and data structures.
The use case I'm thinking of might be that some wants an Object which inherits from 2 Types. E.g. implements 2 interfaces
:
public class Foo { public <T extends Bar & Baz> Foo(T barAndBaz){ barAndBaz.barMethod(); barAndBaz.bazMethod(); } }
Though I have never used it in production.
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