开发者

can we have C++ type enum in java?

开发者 https://www.devze.com 2023-03-26 17:44 出处:网络
hi in C++ we can have enum of follwoing type: enum e_acomany {Audi=4,BMW=5,Cadillac=11,Ford=44,Jaguar=45,Lexus,Maybach=55,RollsRoyce=65,Saab=111};

hi in C++ we can have enum of follwoing type:

enum e_acomany {    Audi=4,     BMW=5,      Cadillac=11,    Ford=44,    Jaguar=45,      Lexus,      Maybach=55,     RollsRoyce=65,      Saab=111  };

can we h开发者_如何学编程ave the similar enum in java. This question might seems childish but i am new to java enum please give me the answer and also provide some links to example.


You can define enum values with associated numbers:

public enum Company {

    AUDI(4), BMW(5), CADILLAC(11), FORD(44), JAGUAR(45), ...;

    private final int id;

    private Company(int id) {
        this.id = id;
    }
}

You can then write your own method to convert an id to a Company value. But fundamentally enums are pretty different in Java to C++, and you may well not want to use them in exactly the same situations.


Pretty much yes. yet the syntax is a bit different. look here: http://download.oracle.com/javase/1,5.0/docs/guide/language/enums.html


Yes, enums exist in Java (Since version 5 I believe)

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}

See http://download.oracle.com/javase/tutorial/java/javaOO/enum.html


Yes. Define your enum this way:

public enum Color {
    RED, GREEN, BLUE
}

and use it like this:

Color carColor = RED;
if ( carColor == RED )
    carColor = BLUE;
0

精彩评论

暂无评论...
验证码 换一张
取 消