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