Declare Variable Generic Type

0

I want that when you declare variable2 is the type of variable that you assign about <Pcambiar>

In courses I saw it like that but I do not know what I'm wrong about

class Hola <Pcambiar>{

public Hola(Pcambiar variable1) {
    Pcambiar variable2 = 5; ////aqui mi da error

    System.out.println("esta es la variable:"+variable1);


}

}

    
asked by Jaime Saiag 14.09.2016 в 17:35
source

2 answers

3

If the variable is generic, you can not assign it a random value. In this case, the type Pcambiar will depend on what the class needs. Imagine not using generics and instead you should use a real class like String instead of where Pcambiar , then the code would look like this:

public Hola(String variable1) {
    //Error aquí. No se puede asignar un entero (int) a un String
    String variable2 = 5;
    System.out.println("esta es la variable: " + variable1);
}

The idea of generics is to help define methods that can be used for many classes or for a group of classes that meet certain criteria such as extending an interface or abstract class. In addition, to assign the value of a generic, you should do it in the constructor or in a set method using a variable of the same generic type.

Sample code based on your current code:

public class Hola <Pcambiar>{
    public Hola(Pcambiar variable1) {
        Pcambiar variable2 = variable1;
        System.out.println("esta es la variable: " + variable2);
    }

    public static void main(String[] args]) {
        //mira que el argumento sea del tipo de clase que estamos enviando
        new Hola<String>("Jaime");
        //los genéricos son solo para clases, no para primitivos
        new Hola<Integer>(5);
        //igual aquí, por ello debemos colocar 10L y no 10
        //sino dará error de compilación
        new Hola<Long>(10L);
        //funciona con cualquier clase
        //agrega el import adecuado: import java.math.BigDecimal
        new Hola<BigDecimal>(new BigDecimal("10.0"));
    }
}

Exit:

esta es la variable: Jaime
esta es la variable: 5
esta es la variable: 10
esta es la variable: 10.0
    
answered by 14.09.2016 / 17:59
source
0

I think you're deviating a bit from the concept of generics and its functionalities. I recommend you read this publication: Using Java Generics

    
answered by 14.09.2016 в 17:58