Skip to main content

Tipo Enum en java 5

Encontré un articulo interesante que habla de los tipos enum en java, y bueno aqui está:

En Java 5 se permite que una variable tenga solo un valor dentro de un conjunto de valores predefinidos, en otras palabras, valores dentro de una lista enumerada. Los tipos enumerados sirven para restringir la selección de valores a algunos previamente definidos, p. ej., si tenemos una aplicación para la venta de café en vasos de diferentes tamaños pero no queremos que los tamaños sean diferentes a CHICO, MEDIANO y GRANDE, podemos crear un tipo enumerado para delimitar dicha selección:


enum TamanoDeCafe{CHICO,MEDIANO,GRANDE};

Posteriormente, al elegir un tamaño de café podemos hacerlo de la siguiente manera:

TamanoDeCafe tdc = TamanoDeCafe.MEDIANO;


No es necesario que las constantes dentro de los enums estén en mayúsculas pero en las convenciones de código de Sun se pide hacerlo de esta manera. Se debe tomar en cuenta que un tipo enumerado puede ser declarado dentro o fuera de una clase, pero NO dentro de un método. P. ej.:


enum instrumentos{
GUITARRA, TROMPETA, BATERIA, BAJO
};

public class Enumerados {

public Enumerados() {
}

public static void main (String... args){
instrumentos in = instrumentos.BATERIA;
System.out.println(in);
EnumDentroClase edc = new EnumDentroClase();
edc.tamano = EnumDentroClase.TamanoDeCafe.CHICO;
System.out.println(edc.tamano);
}

}

class EnumDentroClase{

enum TamanoDeCafe {GRANDE,MEDIANO,CHICO};

TamanoDeCafe tamano;
}

Nota: el punto y coma (;) al final de la declaración del tipo enumerado es opcional.

Al ejecutar el código anterior, obtenemos:

BATERIA
CHICO


Los tipos enumerados no son enteros o cadenas, cada uno es simplemente una instancia del tipo enumerado del que es declarado. Se puede pensar como una especie (no exactamente) de arreglo de variables estáticas finales. Además de constantes dentro de un tipo enumerado, existen algunas otras cosas que puede tener.


Declarar constructores, métodos y variables dentro de un tipo enumerado::


Debido a que los tipos enumerados son como una clase de tipo especial en Java, hay muchas cosas que se pueden realizar dentro de un enum, además de declarar constantes, un tipo enumerado puede contener constructores, métodos y variables.



Tomando nuestro ejemplo del tamaño de café, podemos pensar en escenario donde además de saber el tamaño del café necesitemos la cantidad en onzas de cada tamaño, esto podemos hacerlo de la siguiente manera:


enum TamanoCafe{

CHICO(5), MEDIANO(8), GRANDE(10);

private int onzas;

TamanoCafe(int onzas){
this.onzas = onzas;
}

public int getOnzas(){
return this.onzas;
}

}

public class Cafe {
TamanoCafe tc;
public Cafe() {
}

public static void main(String... args){
Cafe c1 = new Cafe();
Cafe c2 = new Cafe();
c1.tc = TamanoCafe.GRANDE;
c2.tc = TamanoCafe.CHICO;

System.out.println("Tamaño de café 1(c1): "+c1.tc);
System.out.println("Tamaño de café 2(c2): "+c2.tc);

System.out.println("Onzas 1(c1): "+c1.tc.getOnzas());
System.out.println("Onzas 2(c2): "+c2.tc.getOnzas());
}

}

Al ejecutar el código anterior obtendremos lo siguiente:

Tamaño de café 1(c1): GRANDE
Tamaño de café 2(c2): CHICO
Onzas 1(c1): 10
Onzas 2(c2): 5

Algunos puntos importantes sobre los constructores de los tipos enumerados:


+ No se puede invocar al constructor directamente, este se invoca una vez que se crea el tipo enumerado y es definido por los argumentos utilizados para crearlo.

+ Se puede definir más de un argumento en un constructor de un tipo enumerado, asimismo, se puede definir más de un constructor para un tipo enumerado siempre y cuando este tenga argumentos diferentes(sobrecargar el constructor).

Comments

Popular posts from this blog

Quarkus goes Reactive☢

In this tutorial I will explain how to create a quarkus based java application that will use reactive datasource to connect to a postgres database and be able to perform crud operations via rest endpoint. To make it more real this application will also be published into kubernetes cluster and will use configmap to store datasource configuration. To lern more about benefits of reactive data sources vs. jdbc regular data sources you can go to following link https://cutt.ly/1l260tK.  Step 1: Configure Project 

Configuring web application with gwt+spring+hibernate

Building a web application using hibernate, spring and gwt. This time we will show how to create and cofigure an application that will use hibernate , spring and gwt. I will use HR sample database that comes with OracleXE. First , you have to create a GWT project (you can follow the steps for that on  https://developers.google.com/web-toolkit/ ) After you have the project created you need to create a tree of packages like that: Open HumanResources.gwt.xml and add the following line : By doing that you tell gwt to include model package and all dependent packages into gwt compilation Now we can start configuring spring and hibernate. to configure spring first you have to add the following lines on web.xml This will allow spring context to start doing its business. The you will have to create a field called "app-config.xml" in which you will define the settings for spring and hibernate. Over this app-config file first configure the properties as follo...

Configuring web application with gwt+spring+hibernate (continued)

Last Time we learned how to configure a hibernate+ spring+ GWT application. Now we will continue explaining how I built this  application. First, we'll start with the Beans. For this example we will define one bean called Regions and an interface called Bean . Region will be the pojo class that contains the mapping for HR schema regions table The  @Entity  annotation is used to mark this class as an Entity bean. To use this annotation the class must have at least a package scope no-argument constructor. The  @Table  annotation is used to specify the table to persist the data. The  name  attribute refers to the table name. If  @Table  annotation is not specified then Hibernate will by default use the class name as the table name. The  @Id  annotation is used to specify the identifier property of the entity bean. The placement of the @Id  annotation determines the default access strategy that Hibernate will use f...