[英]How can I access an inner class?
For a school project we have been provided code in one of the classes which looks like this 对于一个学校项目,我们在其中一个类中提供了如下代码:
public class Outer{
private enum Inner{
NORTH,
SOUTH,
EAST,
WEST;
}
}
We have not yet been taught how to use this, as it's an extension for self learning. 我们还没有教过如何使用它,因为它是自学的扩展。 So I was wondering how do I get for example "NORTH" as an Inner object which I can then declare as 所以我想知道如何获取“ NORTH”作为内部对象,然后可以将其声明为
Inner i = ?
Thanks a lot, hopefully this makes sense. 非常感谢,希望这是有道理的。
As your enum is marked private
you can only access it from within class outer
. 因为您的枚举被标记为private
您只能从outer
类访问它。 You do this simply by using: 您只需使用以下方法即可:
Inner i = Inner.EAST;
But I think your question is about how to access this enum from outside the class. 但是我认为您的问题是关于如何从课堂之外访问此枚举。 You have to change it's access modifier to public
and then you can use it in other classes like this: 您必须将其访问修饰符更改为public
,然后才能在其他类中使用它,如下所示:
Outer.Inner i = Outer.Inner.EAST;
You can - deliberately - expose NORTH
to an outer object but they will not know much about Inner
they will only know the normal details available to an Enum
(which is actually quite a lot and includes all of the other enum
entries). 您可以-故意-将NORTH
暴露给外部对象,但他们对Inner
了解不多,他们只知道Enum
可用的常规细节(实际上很多,并且包括所有其他enum
项)。
public static class Outer {
private enum Inner {
NORTH,
SOUTH,
EAST,
WEST;
}
public Enum exposeInner () {
return Inner.NORTH;
}
}
You can use private enums in basic three ways inside a class. 您可以在类内以三种基本方式使用私有枚举。 There are situations private enums are used inside a class. 在某些情况下,在类内使用私有枚举。
method 1: enumName.Value. 方法1:enumName.Value。 Eg Inner.NORTH 内在北方
method 2 (special case): if you are in a switch statement and enum variable is used as the selector, then you can directly use the value without enum name. 方法2(特殊情况):如果您在switch语句中,并且使用enum变量作为选择器,则可以直接使用不带enum名称的值。 Eg case NORTH: 例如北:
method 3: you can use the values method to get the array consisting all the values of the enum. 方法3:您可以使用values方法来获取包含枚举的所有值的数组。 Eg (for the first element): Inner.values()[0] 例如(对于第一个元素):Inner.values()[0]
public class Outer{
private enum Inner{
NORTH,
SOUTH,
EAST,
WEST;
}
public static void main(String[] args) {
Inner i = Inner.NORTH;
System.out.println("i = " + i + "\n");
System.out.print("Switch Statement: \n" +
"i = ");
switch(i) {
case NORTH:
System.out.println(Inner.NORTH);
break;
case SOUTH:
System.out.println(Inner.SOUTH);
case EAST:
System.out.println(Inner.EAST);
case WEST:
System.out.println(Inner.WEST);
default:
System.out.println(i);
}
System.out.println("\nUsing values method: ");
for (Inner value : Inner.values())
System.out.println("value = " + value);
System.out.println("value of first element in the arra = " + Inner.values()[0]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.