Java 1.6中的Enum类主体功能 [英] Enum class body feature in Java 1.6

查看:65
本文介绍了Java 1.6中的Enum类主体功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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的一个特定于常量的类的示例。如何执行此操作并查看结果输出?

This is a SCJP 1.6 question from K&B 6 book. This is an example of Constant Specific Class Body as a feature of SCJP 6. How do I execute this and see the resultant output?

我有2个问题:


  1. 我的Java main方法是什么样的?请帮助我执行此部分代码。我无法理解输出的行为。

  1. What does my Java main method look like ?Please help me to execute this partial code. I'm unable to understand how the output behaves.

getLidCode()方法的工作方式在Java 1.6的此类主体中?

How does the getLidCode() method work in this class body in Java 1.6 ?


推荐答案

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

What you call a Constant Specific Class Body is what the JLS refers to as an optional class body for an enum constant. It's implemented as an anonymous inner class that extends the outer, enclosing enum. So in your case, the enum constant OVERWHELMING will be of an anonymous inner type that extends CoffeeSize, and overrides the method getLidCode(). In pseudocode, the inner class looks something like this:

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

调用 getLidCode()在常量 BIG HUGE 上将调用基本枚举实现,而调用相同的实现 OVERWHELMING 上的方法将调用该方法的替代版本,因为 OVERWHELMING 实际上是另一种类型。要进行测试,只需运行代码以调用不同枚举常量的 getLidCode()

Calling getLidCode() on either the constant BIG or HUGE will invoke the base enums implementation, whereas invoking the same method on OVERWHELMING will invoke the overriden version of the method, since OVERWHELMING is actually of a different type. To test, simply run code to invoke the getLidCode() of the different enum constants.

System.out.println(CoffeeSize.BIG.getLidCode());
System.out.println(CoffeeSize.HUGE.getLidCode());
System.out.println(CoffeeSize.OVERWHELMING.getLidCode());

这篇关于Java 1.6中的Enum类主体功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆