-2

I am working on a Java application in which I found this class:

public class TipologiaGenerica<K> {
    private K codice;
    private String descrizione;

    public TipologiaGenerica(K codice, String descrizione) {
        this.codice = codice;
        this.descrizione = descrizione;
    }
    public K getCodice() {
        return codice;
    }

    public void setCodice(K codice) {
        this.codice = codice;
    }
    public String getDescrizione() {
        return descrizione;
    }
    public void setDescrizione(String descrizione) {
        this.descrizione = descrizione;
    }

}

As you can see this class is declared as: TipologiaGenerica and K seems to be something like an object type that could be passed when a specific TipologiaGenerica object is created and that determinate the type of one of its inner field, this one:

private K codice;

Infact, somewhere else in the code, I find a TipologiaGenerica object creation:

TipologiaGenerica<String> dataPerLista = new TipologiaGenerica<String>(dataString, dataString);

What exatly mean? I think that doing in this way it is creating a specific TipologiaGenerica object having the inner codice field that is a String.

Is it my reasoning correct? What is the name of this specific use of Java? What are the most common purpose of this type of constructor?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • You tagged your question "generics", named your class `TipologiaGenerica` but you didn't know what feature you're using...? – kryger Dec 07 '15 at 10:30
  • @kryger He is probably not asking because he doesn't know, but because he feels SO lacks a good question on the basics of generics in java. – Klas Lindbäck Dec 07 '15 at 11:07

3 Answers3

3

It is called Generic Types. You can use them to generalize some classes / methods into typesafe code "templates".

Check the Oracle's tutorial regarding this topic

https://docs.oracle.com/javase/tutorial/java/generics/

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
3

Is it my reasoning correct?

yes.

What is the name of this specific use of Java?

Generics

What are the most common purpose of this type of constructor?

type safety

hahn
  • 3,588
  • 20
  • 31
1

This is called generics in Java. The use of this type of programming is to ensure type safety and that you could reuse the same parent class by inserting various object types. for e.g. in your case, you have made

TipologiaGenerica<String>

Users can reuse the same class for other types, for e.g.

TipologiaGenerica<Integer>
achin
  • 169
  • 8