SCJP 5.0 Study Notes(3)

Java枚举深入解析
本文详细介绍了Java中枚举类型的使用方法,包括枚举的基本定义、构造器的应用、实例变量及方法的实现等。此外,还列举了一些复杂案例,帮助读者理解如何在实际开发中灵活运用枚举。

 

Enums

<!---->·    <!---->myEnum.valueOf(String) – returns value of corresponding enum value

<!---->·    <!---->yourEnum.values() lists all the possible values of yourEnum

<!---->·    <!---->Enums can have instance/member variables, constructors, and methods

<!---->·    <!---->Enums constructors can have a constant specific class body (a method that overrides one of the methods), but not any new methods? or any method calls

<!---->·    <!---->In an enum declaration, multiple constant-specific methods for each enumerated type must be separated by commas and terminated by a semi-colon:  e.g.      enum VALUE{ MAX {int returnIt(int x) {return 10}; },

                                                 MIN {int returnIt{(int x) {return 1};};}

<!---->·    <!---->enums can be imported using “import package.EnumClass.*”, “import package.EnumClassor.EnumName”, “import static” versions

<!---->·    <!---->enum constructors can neber be invoked directly from code

 

Simple Example

enum Month{NOV, DEC, JAN};  // The semi-colon at the end in this case is optional

 

More Complex

enum Month {                       // Any access mod -- SAME class, default/pub – own class

         NOV, DEC(11), JAN, FEB; //  Must end in semicolon if more than just declarations

         Month(){}           //  No-arg constructor only auto-created by JVM     

         Month(int index) {                 //  if no other constructor provided – just like classes

                   this.index = index;

         }

         int index;                       // Initialized automatically, can have any access modifier     

};                                  // This semicolon is optional

        

for (Month month: Month.values()) {      //notice values() method

         System.out.println("Day = " + month);

}                

Month month = Month.DEC;        

switch (month) {

         case DEC : System.out.printf("%s %d %b","November", 264, true);    //CAN’T use Month.DEC in case – won’t compile

}

 

Really Complex

         enum Month {

                   NOV("November", 11),                          // Notice various constructor formats that all compile and run

                   DEC("December"),

                   JAN {int getIndex(){return 55;}},                    // Notice overriden method here.   CAN’T be new method – doesn’t compile

                   FEB(),

                   MAR;

                  

                   Month(){}          

                   Month(String name, int index) {

                            this.index = index;

                   }

                   Month(String name) {

                            this.name = name;

                   }

                   protected int index;

                   String name;

                   int getIndex(){    

                            return this.index;

                   }

                   String getName(){

                            return this.name;

                   }

         };

 


Gotchas (very tricky stuff)

<!---->·    <!---->Watch for faulty method returns, either returning types different than declared type or failing to return something, or returning something when void is declared, or not returning something if a return type was specified.

<!---->·    <!---->Watch for methods parading as constructors – constructors do not have return values!

<!---->·    <!---->If there is a method call to methods with the same name and with (String[] args) and (String… args), the code won’t compile b/c it won’t know which method to call

<!---->·    <!---->Remember that after threadName.start() is declared, the thread my not enter the running state until all the code after it has been executed

<!---->·    <!---->The class has a lock, and each object has a lock, and notify() and notifyAll() only notify threads waiting for the SAME LOCK

<!---->·    <!---->Static methods can’t override non-static methods and vice-versa – will not compile

<!---->·    <!---->Watch out for statements that the compiler knows will never be reached (like after throwing an exception) – this code will not compile

<!---->·    <!---->new Boolean(“TRue”) results in true, new Boolean(“AnythingOtherThanCaseInsensitiveTrue”) is false, boolean x = true or false (boolean x=True or boolean x=TRUE will not compile)

<!---->·    <!---->in System.out.format/printf(“%b”, varX) will print true if varX has any value

<!---->·    <!---->If Subclass is in a different package than Superclass, any protected variables in Superclass can only be reached from the main(0 in Subclass using an object reference to Subclass, not Superclass

<!---->·    <!---->When wait() and notify() methods are called from non-sychronized context, code will compile, but IllegalMonitorStateException will be thrown at runtime

<!---->·    <!---->HashMap and LinkedHashMap can have 1 null key and multiple null values, but TreeMap can’t have any null keys (can have null values), and Hashtable can’t have any null keys or values (will result in NullPointerException)

<!---->·    <!---->Use of collectionType.toArray() and trying to use as array as specific types, without casting, when toArray() returns Objects.

<!---->·    <!---->Static member variables are automatically initialized, final member variables must initialized by the time the constructor finishes, and static final member variables must be assigned at time of declaration or in a static initialization block.  Breaking these rules results in failed compilation

<!---->·    <!---->Classes can have multiple static initialization blocks and instance initialization blocks, which I think run in the order listed

<!---->·    <!---->Can’t assume from listed code that a property value hasn’t already been set for use of System.getProperty(stringKey, stringDefaultValue), so can’t tell if property will be set to stringDefaultValue or not

<!---->·    <!---->Watch out for trying to use elements of raw type (non-generic) collections without casting

<!---->·    <!---->Watch out for static methods trying to make a reference to “this”

<!---->·    <!---->Illegal to try to return literal 1.2 when return type is a float (the literal 1.2 is a double)

<!---->·    <!---->Any methods implemented from an interface MUST be public since an interface’s methods are always public

<!---->·    <!---->Get suspicious when you see the protected access modifier – they are probably going to try to illegally access it from outside the package (you can only acces it through inheritance, not through an instantiation of the object with the protected member

 

Exam Tips

<!---->·    <!---->After finishing, go back and check every question for:

         --calling non-static methods or using non-static variables in main

         --for any Thread question, all wait(), sleep(), and join() methods handle the InterruptedException

         --modifying strings but not having a reference to new modified string

<!---->·    <!---->Get suspicious when there is a mix of raw type collections and generic type collections

<!---->·    <!---->If question code contains packages and imports, watch out for probable errors using these.

 

转自:

http://holoquest.org/other/scjp5_webnotes.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值