简体   繁体   中英

Why do I need to import enum classes to use them when I already imported the package they're in? [Java]

I'm having a little confusion regarding importing packages in Java.

So I have a class with nested enum classes inside:

public class AirCraft extends PublicTransportation 
{
    private AirType classType;
    private TimeType maintainType;
    
    //default constructor
    public AirCraft() {
        super();
        classType = AirType.NONE;
        maintainType = TimeType.NONE;
    }
    
    //nested enums used for AirCraft attributes (2)
    public enum AirType {
        NONE,
        HELICOPTER,
        AIRLINE,
        BALLOON,
        GLIDER
    }
    
    public enum TimeType{
        NONE,
        WEEKLY,
        MONTHLY,
        YEARLY
    }

Then in my driver class I have:

import airTransport.*; //importing the AirCraft class in which resides the two enum classes

public class DriverTransport {

    public static void main(String[] args) {
        //testing AirCraft class methods
        AirCraft secondAir = new AirCraft(50.9, 10, AirType.HELICOPTER, TimeType.MONTHLY);
    }
}

However, I receive a "cannot be resolved to a variable" error for AirType and TimeType. It is fixed if I import them separately, but I'd like to understand why simply importing AirCraft class does not work even though these two enums are inside AirCraft class.

Thanks.

You have used inner enumeration so you have to refer to it via the class it is in:

AirCraft secondAir = new AirCraft(50.9, 10, AirCraft.AirType.HELICOPTER, AirCraft.TimeType.MONTHLY);

you can also statically import the entire enum and use it the way you originally wanted:

import static other.AirCraft.*;

and then:

AirCraft secondAir = new AirCraft(50.9, 10, AirType.HELICOPTER, AirCraft.TimeType.MONTHLY);

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