为什么 Java 不允许在方法中定义枚举?

编程入门 行业动态 更新时间:2024-10-11 21:26:13
本文介绍了为什么 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 不允许在方法中定义枚举?

本文发布于:2023-11-09 04:13:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571374.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不允许   定义   方法   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!