Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What purpose do generic constructors serve in Java?

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?

like image 325
0xbe5077ed Avatar asked Dec 14 '17 05:12

0xbe5077ed


People also ask

What is the purpose of generics in Java?

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.

What is a generic constructor in Java?

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.

What is the main purpose of constructors in Java?

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.

What is the purpose of generic programming?

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.


1 Answers

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.

like image 116
Lino Avatar answered Sep 29 '22 14:09

Lino