2

Unable to access values from enum defined outside class Test.

How to access enumeration constant like Reddel,Jonathan,Goldendel etc

enum Apple{
    Reddel,Jonathan,Goldendel,Winesap,Cortland;
}


public class Test{
    enum Apple{
        Seb,Majj,Dlred,Wipe,Cland;
    }
    public static void main(String s[]){
        //here I want to access enumeration constant from Apple outside Test.
        //Apple.Winesap
        //Apple.Goldendel
        System.out.println(Apple.Winesap);

    }
}
aioobe
  • 413,195
  • 112
  • 811
  • 826

4 Answers4

3

If you have your classes in a package, say

package pkg;

then using pkg.Apple.Winesap will work. (The fully qualified name of the other Apple is pkg.Test.Apple.)

You can also statically import the members from pkg.Apple:

import static pkg.Apple.*;

and then use Winesap.

If you're using the default package (no package declaration) then the inner Apple shadows the other Apple and you're out of luck. (Same goes for static imports; You can't statically import a member from a class in the default package.)

Related questions:

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
0

The package name should be appended.

Zefick
  • 2,014
  • 15
  • 19
0

You need to specify the full package path. The below code I tested is compiling:

package com.my.test;

enum Apple{
    Reddel,Jonathan,Goldendel,Winesap,Cortland;
}

public class Test{
    enum Apple{
        Seb,Majj,Dlred,Wipe,Cland;
    }
    public static void main(String s[]){
        //here I want to access enumeration constant from Apple outside Test.
        //Apple.Winesap
        //Apple.Goldendel
        System.out.println(com.my.test.Apple.Winesap);
        }
    }
TheCodingFrog
  • 3,406
  • 3
  • 21
  • 27
0

The enum is declared somewhere, imagine in ClassName.java. You can refer them separately with ClassName.Apple.Reddel and Test.Apple.Seb

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109