Thursday, August 5, 2010

Enums: Bridge.java

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)
Chapter 3, Question 7

Code was modified


This code compiles and runs

line 12: The getBidValue() method in NOTRUMP overrides the getBidValue() method that is part of Suits (please refer to lines 4 and 5). Output is

100

line 13: HEARTS is an object of type Suits, and it invokes SuitsgetBidValue()method. Output is

90

line 14: (Courtesy of coderanch.com): Suits.SPADES is an enum constant. An enum constant is internally a final static reference of the enum type Suits. When Suits.SPADES is referred to in the function System.out.println, toString() function of this reference will be invoked. Default toString() function of the enum class invokes the name() function of the enum class which returns the constant name as declared in the enum, i.e. SPADES If you refer to line 9, you will note that toString() has been overidden to that the name is printed in all lowercase, hence spades will print. In our example, the same System.out.println also has the argument Suits.SPADES.points, which is established when the object Suits.SPADES is first created, as shown in line 3. Output

spades 30

line 15: values() method returns an array reference, not the contents of the enum. Output

[LBridge$Suits;@addbf1

line 16: to print contents of Suits, create an array of Suits and assign it to the array reference returned by Suits.values()

line 17: enhanced for loop declares i as type Suits, and iterates over s, the array of Suits

line 18: every time the loop from line 17 iterates, it prints the content of Suits. Output

clubs
diamonds
hearts
spades
notrump


No comments:

Post a Comment