为什么Java不允许在方法中定义枚举? [英] Why doesn't Java allow enum to be defined within a method?

查看:190
本文介绍了为什么Java不允许在方法中定义枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java:本地枚举

为什么我们无法在特定方法中定义枚举在java中?如果我有一个场景,我将在一个方法中使用这些枚举值,而不是在任何其他地方。在全球范围内声明方法而不是定义它不是很好吗?我的意思是公开或默认。

Why do we cannot define enum within a specific method in java? If I have a scenario where I will be using those enum values in a method only not at any other place. Wouldn't it be nice to declare in method rather defining it at globally? i mean as public or default.

推荐答案

您不能在方法级别定义 JavaDocs 。 (我想看到允许的语言)

You cannot define at the method level as stated by the JavaDocs. (I would like to see a language that allowed that)


嵌套枚举类型是隐式静态的。允许明确声明嵌套的枚举类型为静态。

Nested enum types are implicitly static. It is permissible to explicitly declare a nested enum type to be static.

这意味着无法定义本地(§14.3)枚举或定义枚举在一个内部类(§8.1.3)中。

This implies that it is impossible to define a local (§14.3) enum, or to define an enum in an inner class (§8.1.3).

你可以做什么在类级别声明它,在方法级别:

What you can do it declare it at the class level and a variable at the method level:

public class Light {
    ...
    private LightSwitch position;
    private enum LightSwitch {
        On,
        Off
    }
    public void SwitchOn() {
        Switch(LightSwitch.On);
    }
    public void SwitchOff() {
        Switch(LightSwitch.Off);
    }
    private void Switch(LightSwitch pos) {
        position = pos;
    }
}

这篇关于为什么Java不允许在方法中定义枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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