標籤:
1 public final class ThreeStooges { 2 3 4 /* 5 * stooges是Set<String>類型的引用,final限定該引用成員屬性stooges被賦初值後,就不能再改變去引用其他的同類對象 6 * final只是限定了聲明的引用stooges不能改變,stooges引用的對象能不能改變,由被引用對象本身的類定義來決定 7 */ 8 private final Set<String> stooges = new HashSet<String>(); 9 10 public ThreeStooges() {11 stooges.add("Moe");12 stooges.add("Larry");13 stooges.add("Curly");14 15 //stooges = new HashSet<String>(); //The final field ThreeStooges.stooges cannot be assigned16 }17 18 /**19 * 向被引用的HashSet中添加一個元素20 * final域stooges仍引用著賦初值時的那個HashSet對象,而stooges.add(name);只是向被引用的被引用的HashSet中添加一個元素21 * @param name22 */23 public void add(String name) {24 stooges.add(name);25 }26 27 28 public boolean isStooge(String name) { 29 return stooges.contains(name);30 }31 32 33 public void print() {34 Iterator<String> iterator = stooges.iterator();35 while (iterator.hasNext()) {36 System.out.println(iterator.next() + ", ");37 }38 }39 40 41 public static void main(String[] args) {42 43 44 ThreeStooges ts = new ThreeStooges();45 ts.add("asn");46 ts.print(); 47 }48 }
輸出:
Moe,
asn,
Curly,
Larry,
java final域