访问枚举中的常量

访问枚举中的常量

本文介绍了Java:访问枚举中的常量(枚举)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读SCJP书,我在第1章自我测试中找到了这样的一个例子:

reading the SCJP book, I've found something like this in the chapter 1 "self-test" :

enum Animals {
    DOG("woof"), CAT("meow"), FISH("burble");
    String sound;
    Animals(String s) { sound = s; }
}

class TestEnum {
    static Animals a;
    public static void main(String[] args) {
        System.out.println(a.DOG.sound + " " + a.FISH.sound);

        // the following line is from me
        System.out.println(Animals.DOG.sound + " " + Animals.FISH.sound);
    }
}

注意:代码编译正常。
我不明白为什么我们可以从变量 a 访问DOG,CAT或FISH常量。我认为(这也是写在书中),DOG,FISH,CAT是常数的方式是以类似于的方式实现的。public static final动物DOG =新动物(1);
所以如果他们真的是静态的为什么我们可以从 a 访问它们?
最后一行是我熟悉的方式。

Note: the code compile fine.What I don't understand is why we can access the DOG, CAT or FISH constants from the variable a. I thought (and it is also written in the book) that the DOG, FISH, CAT being constants are implemented in a way similar to public static final Animals DOG = new Animals(1);So if they really are static why can we access them from a ?The last line is the way I am familiar with.

推荐答案

写作 a.DOG 与写入 Animal.DOG 相同。也就是说,编译器将使用其编译时类型Animal替换变量。它被认为是错误的代码,因为它隐藏了它依赖于编译时类型而不是动态类型 a 的事实。

Writing a.DOG is the same as writing Animal.DOG. That is, the compiler will replace the variable with its compile time type Animal. It is considered bad code since it hides the fact that it relies on the compile time type instead of the dynamic type of a.

这篇关于Java:访问枚举中的常量(枚举)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:05