7
enum CoffeeSize{               
      BIG(8),   
      HUGE(10),   
      OVERWHELMING(16) {   

       public String getLidCode(){   
            return "A";   
       }   
      };   

    private int ounces;   

    public int getOunces(){   
         return ounces;   
    }    

    CoffeeSize(int ounces){   
        this.ounces = ounces;   
    }   

    public String getLidCode(){   
            return "B";   
    }   
}  

这是 K&B 6 书中的 SCJP 1.6 问题。这是作为 SCJP 6 功能的常量特定类主体的示例。我如何执行它并查看结果输出?

我有两个问题:

  1. 我的 Java 主要方法是什么样的?请帮我执行这个部分代码。我无法理解输出的行为。

  2. getLidCode()该方法在 Java 1.6 的此类主体中如何工作?

4

2 回答 2

16

您所说的常量特定类主体是JLS所指的枚举常量的可选类主体。它被实现为一个匿名的内部类,它扩展了外部的封闭枚举。因此,在您的情况下,枚举常量OVERWHELMING将是一个匿名内部类型,它扩展CoffeeSize并覆盖方法getLidCode()。在伪代码中,内部类看起来像这样:

class CoffeeSize$1 extends CoffeeSize {
    @Override
    public String getLidCode() {
        return "A";
    }
}

调用getLidCode()常量BIGHUGE将调用基本枚举实现,而调用相同的方法OVERWHELMING将调用该方法的覆盖版本,因为OVERWHELMING实际上是不同的类型。要进行测试,只需运行代码来调用getLidCode()不同的枚举常量。

System.out.println(CoffeeSize.BIG.getLidCode());
System.out.println(CoffeeSize.HUGE.getLidCode());
System.out.println(CoffeeSize.OVERWHELMING.getLidCode());
于 2013-03-08T18:46:16.660 回答
3
I have executed my answer,as below.Please correct me if im wrong.output is given. 

干杯:-))

public class EnumOverriddenExample {
enum CoffeeSize{               
      BIG(8),   
      HUGE(10),   
      OVERWHELMING(16){   

           public String getLidCode(){   
                return "A";   
           }   
      };

    CoffeeSize(int ounces){   
            this.ounces = ounces;   
    }

    private int ounces;   

    public int getOunces(){   
         return ounces;   
    }   

    public void setOunces(int ounces){   
         this.ounces=ounces;   
    }

    public String getLidCode(){   
            return "B";   
    }   
}  
public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("CoffeeSize for BIG is "+EnumOverriddenExample.CoffeeSize.BIG.getLidCode());
    System.out.println("CoffeeSize for HUGE is "+EnumOverriddenExample.CoffeeSize.HUGE.getLidCode());
    System.out.println("CoffeeSize for OVERWHELMING is "+EnumOverriddenExample.CoffeeSize.OVERWHELMING.getLidCode());

    System.out.println("CoffeeSize for BIG is "+EnumOverriddenExample.CoffeeSize.BIG.getOunces());
    System.out.println("CoffeeSize for HUGE is "+EnumOverriddenExample.CoffeeSize.HUGE.getOunces());
    System.out.println("CoffeeSize for OVERWHELMING is "+EnumOverriddenExample.CoffeeSize.OVERWHELMING.getOunces());

}

}

Output is below
-----------------------------------
CoffeeSize for BIG is B --> returns "B"
CoffeeSize for HUGE is B -->returns "B"
CoffeeSize for OVERWHELMING is A--constant specific class body returns "A"
CoffeeSize for BIG is 8
CoffeeSize for HUGE is 10
CoffeeSize for OVERWHELMING is 16
------------------------------------
于 2013-03-09T12:53:26.430 回答