简体   繁体   中英

Why aren't byte arguments recognized as integers?

I have the following enum:

public enum Months {
    JAN(31),
    FEB(28),
    MAR(31),
    APR(30),
    MAY(31),
    JUN(30),
    JUL(31),
    AUG(31),
    SEP(30),
    OCT(31),
    NOV(30),
    DEC(31);

    private final byte DAYS; //days in the month

    private Months(byte numberOfDays){
        this.DAYS = numberOfDays;
    }//end constructor

    public byte getDays(){
        return this.Days;
    }//end method getDays
}//end enum Months

It gives me an error that says "The constructor Months(int) is undefined" although I am passing a valid byte arguments. What am I doing wrong?

The simplest solution is to accept an int value

private Months(int numberOfDays){
    this.DAYS = (byte) numberOfDays;
}

BTW non-static fields should be in camelCase not UPPER_CASE

Also FEB has 29 days in some years.

public static boolean isLeapYear(int year) {
    // assume Gregorian calendar for all time
    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

public int getDays(int year) {
    return days + (this == FEB && isLeapYear(year) ? 1 : 0);
} 

Those numbers are int literals. You'd have to cast them to byte :

 JAN((byte)31),

The Java Language Specification says the following regarding lexical integer literals:

The type of a literal is determined as follows:

  • The type of an integer literal (§3.10.1) that ends with L or l is long (§4.2.1).
  • The type of any other integer literal is int (§4.2.1).

So it requires you to explicitly cast this integer literal to byte.

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