21 dezembro, 2015 3 Comentários AUTOR: elemarjr CATEGORIAS: Java, Programação, Sem categoria Tags:,

Amazing JAVA - Parte 1 - Enums

Tempo de leitura: 2 minutos

Olá,

Até que enfim consigo reunir um pouco de tempo para estudar Java! Há tempos conheço os fundamentos, mas, agora resolvi "saber de verdade".

Claro que há muitas semelhanças entre C# e Java. Entretanto, estou descobrindo alguns tesouros nas diferenças. Vou compartilhar as coisas que considero mais bacanas aqui no blog.

Começamos pelos Enums. Como Josua Bloch explica no excelente Effective Java (2nd Edition):

On the surface, Java's enum types may appear similar to those of other languages, such as C, C++, and C#, but appearances are deceiving. Java's enum type are full-fledged classes, far more powerful than their counterparts in these other languages, where enums are essentially int values.

Vejamos (exemplo também extraído do livro).

enum Planet {
    MERCURY (3.202e+23, 2.439e6),
    VENUS   (4.869e+24, 6.052e6),
    EARTH   (5.975e+24, 6.378e6),
    MARS    (6.419e+23, 3.393e6),
    JUPITER (1.899e+27, 7.149e7),
    SATURN  (5.685e+26, 6.027e7),
    URANUS  (8.683e+25, 2.556e7),
    NEPTUNE (1.024e+26, 2.477e7);

    private final double mass;
    private final double radius;
    private final double surfaceGravity;

    private static final double G = 6.67300E-11;

    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
        this.surfaceGravity = G * mass / (radius * radius);
    }

    public double mass()    { return mass; }
    public double radius()  { return radius; }
    public double surfaceGravity()
    { return surfaceGravity; }

    public double surfaceWeight(double mass) {
        return mass * surfaceGravity;
    }
}

class Sample {
    public static void main(String[] args) {
        for (Planet p: Planet.values()) {
            System.out.printf(
                "Gravity on %s is %f%n",
                p,
                p.surfaceGravity()
            );
        }
    }
}

Bacana não?

Vejamos o que o utilitário Javap nos revela.

final class Planet extends java.lang.Enum<Planet> {
  public static final Planet MERCURY;

  public static final Planet VENUS;

  public static final Planet EARTH;

  public static final Planet MARS;

  public static final Planet JUPITER;

  public static final Planet SATURN;

  public static final Planet URANUS;

  public static final Planet NEPTUNE;

  public static Planet[] values();
    Code:
       0: getstatic     #1                  // Field $VALUES:[LPlanet;
       3: invokevirtual #2                  // Method "[LPlanet;".clone:()Ljava/lang/Object;
       6: checkcast     #3                  // class "[LPlanet;"
       9: areturn

  public static Planet valueOf(java.lang.String);
    Code:
       0: ldc           #4                  // class Planet
       2: aload_0
       3: invokestatic  #5                  // Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
       6: checkcast     #4                  // class Planet
       9: areturn

  public double mass();
    Code:
       0: aload_0
       1: getfield      #7                  // Field mass:D
       4: dreturn

  public double radius();
    Code:
       0: aload_0
       1: getfield      #8                  // Field radius:D
       4: dreturn

  public double surfaceGravity();
    Code:
       0: aload_0
       1: getfield      #11                 // Field surfaceGravity:D
       4: dreturn

  public double surfaceWeight(double);
    Code:
       0: dload_1
       1: aload_0
       2: getfield      #11                 // Field surfaceGravity:D
       5: dmul
       6: dreturn

  static {};
    Code:
       0: new           #4                  // class Planet
       3: dup
       4: ldc           #12                 // String MERCURY
       6: iconst_0
       7: ldc2_w        #13                 // double 3.202E23d
      10: ldc2_w        #15                 // double 2439000.0d
      13: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IDD)V
      16: putstatic     #18                 // Field MERCURY:LPlanet;
      19: new           #4                  // class Planet
      22: dup
      23: ldc           #19                 // String VENUS
      25: iconst_1
      26: ldc2_w        #20                 // double 4.869E24d
      29: ldc2_w        #22                 // double 6052000.0d
      32: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IDD)V
      35: putstatic     #24                 // Field VENUS:LPlanet;
      38: new           #4                  // class Planet
      41: dup
      42: ldc           #25                 // String EARTH
      44: iconst_2
      45: ldc2_w        #26                 // double 5.975E24d
      48: ldc2_w        #28                 // double 6378000.0d
      51: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IDD)V
      54: putstatic     #30                 // Field EARTH:LPlanet;
      57: new           #4                  // class Planet
      60: dup
      61: ldc           #31                 // String MARS
      63: iconst_3
      64: ldc2_w        #32                 // double 6.419E23d
      67: ldc2_w        #34                 // double 3393000.0d
      70: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IDD)V
      73: putstatic     #36                 // Field MARS:LPlanet;
      76: new           #4                  // class Planet
      79: dup
      80: ldc           #37                 // String JUPITER
      82: iconst_4
      83: ldc2_w        #38                 // double 1.899E27d
      86: ldc2_w        #40                 // double 7.149E7d
      89: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IDD)V
      92: putstatic     #42                 // Field JUPITER:LPlanet;
      95: new           #4                  // class Planet
      98: dup
      99: ldc           #43                 // String SATURN
     101: iconst_5
     102: ldc2_w        #44                 // double 5.685E26d
     105: ldc2_w        #46                 // double 6.027E7d
     108: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IDD)V
     111: putstatic     #48                 // Field SATURN:LPlanet;
     114: new           #4                  // class Planet
     117: dup
     118: ldc           #49                 // String URANUS
     120: bipush        6
     122: ldc2_w        #50                 // double 8.683E25d
     125: ldc2_w        #52                 // double 2.556E7d
     128: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IDD)V
     131: putstatic     #54                 // Field URANUS:LPlanet;
     134: new           #4                  // class Planet
     137: dup
     138: ldc           #55                 // String NEPTUNE
     140: bipush        7
     142: ldc2_w        #56                 // double 1.024E26d
     145: ldc2_w        #58                 // double 2.477E7d
     148: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IDD)V
     151: putstatic     #60                 // Field NEPTUNE:LPlanet;
     154: bipush        8
     156: anewarray     #4                  // class Planet
     159: dup
     160: iconst_0
     161: getstatic     #18                 // Field MERCURY:LPlanet;
     164: aastore
     165: dup
     166: iconst_1
     167: getstatic     #24                 // Field VENUS:LPlanet;
     170: aastore
     171: dup
     172: iconst_2
     173: getstatic     #30                 // Field EARTH:LPlanet;
     176: aastore
     177: dup
     178: iconst_3
     179: getstatic     #36                 // Field MARS:LPlanet;
     182: aastore
     183: dup
     184: iconst_4
     185: getstatic     #42                 // Field JUPITER:LPlanet;
     188: aastore
     189: dup
     190: iconst_5
     191: getstatic     #48                 // Field SATURN:LPlanet;
     194: aastore
     195: dup
     196: bipush        6
     198: getstatic     #54                 // Field URANUS:LPlanet;
     201: aastore
     202: dup
     203: bipush        7
     205: getstatic     #60                 // Field NEPTUNE:LPlanet;
     208: aastore
     209: putstatic     #1                  // Field $VALUES:[LPlanet;
     212: return
}

Não restam dúvidas. Enums em Java são classes normais com alguns campos inicializados.

Era isso.

3 Comentários

  1. Tiago Trindade 1 ano ago says:

    Muito Bom Elemar. To estudando estrutura de dados com Java também.
    Como disse o uncle bob no The Clean Coder, é bom que pratiquemos em outras linguagens... Se você programa em c#, pratique com Ruby, se programa em Ruby pratique em Pyton...
    Isso sem dúvidas nos ajuda a evoluir...
    Abraço

    Responder

Trackbacks para este post

  1. Amazing JAVA – Parte 2 – Ainda mais sobre Enums | Elemar DEV
  2. Amazing JAVA – Parte 2 – Ainda mais sobre Enums | Elemar JR