How to static-import enums residing in separate files in Java?

Basically, here's the gist of my code:

// File: ShapeColor.java
package mypackage;

public enum ShapeColor
{
    MAUVE,
    PURPLE,
    VIOLET;
}

// File: ShapeSize.java
package mypackage;

public enum ShapeSize
{
    TINY,
    SMALL,
    MEDIUM,
    LARGE,
    HUGE,
    COLOSSAL;
}

// File: Shape.java
import static mypackage.ShapeSize.*;
import static mypackage.ShapeColor.*;

public class Shape
{
    private ShapeSize size;
    private ShapeColor color;

    public Shape()
    {
        this(ShapeSize.MEDIUM, ShapeColor.PURPLE);
    }

    public Shape(ShapeSize ss, ShapeColor sc)
    {
        this.size = ss;
        this.color = sc;
    }
}

How can I import static my enum definitions so I can access the enum values without qualifying them? I have all my .java source files slapped in one directory and I'm compiling from the command line. I have no idea about packages and how to "organize" my source files in directories (or if I even should do so). I've tried reading about these concepts but all that did was get me more confused. I learn much better through examples and demo code than by reading documentation, unfortunately.

EDIT:

After adding package mypackage; to the enum files and import static mypackage.* to the class file. I get the following errors:

.\ShapeSize.java:4: error: duplicate class: mypackage.ShapeSize public enum ShapeSize ^ Shape.java:7: error: cannot access ShapeSize private ShapeSize size; ^ bad source file: .\ShapeSize.java file does not contain class ShapeSize Please remove or make sure it appears in the correct subdirectory of the sourcepath.

2 Answers

  1. Gabriel- Reply

    2019-11-13

    You can use:

    import static mypackage.ShapeColor.PURPLE;
    import static mypackage.ShapeSize.MEDIUM;
    
  2. Gavin- Reply

    2019-11-13

    Figured it out! Moved both enum source files to sub-folder called mypackage and also normal-imported them in addition to import static their values. Shape class now starts like this:

    import mypackage.ShapeSize;
    import mypackage.ShapeColor;
    import static mypackage.ShapeSize.*;
    import static mypackage.ShapeColor.*;
    

    EDIT: Actually, no need to move the enum source files. Just had to standard-import them.

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>