简体   繁体   中英

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

Inner i = ?

Thanks a lot, hopefully this makes sense.

As your enum is marked private you can only access it from within class 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:

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).

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. 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. Eg case NORTH:

method 3: you can use the values method to get the array consisting all the values of the enum. Eg (for the first element): Inner.values()[0]


Full code is given below:

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]);
    }      

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM