您的位置:首页 > 编程语言 > Java开发

java final域

2015-05-31 15:47 459 查看
public final class ThreeStooges {

/*
* stooges是Set<String>类型的引用,final限定该引用成员属性stooges被赋初值后,就不能再改变去引用其他的同类对象
* final只是限定了声明的引用stooges不能改变,stooges引用的对象能不能改变,由被引用对象本身的类定义来决定
*/
private final Set<String> stooges = new HashSet<String>();

public ThreeStooges() {
stooges.add("Moe");
stooges.add("Larry");
stooges.add("Curly");

//stooges = new HashSet<String>(); //The final field ThreeStooges.stooges cannot be assigned
}

/**
*  向被引用的HashSet中添加一个元素
*  final域stooges仍引用着赋初值时的那个HashSet对象,而stooges.add(name);只是向被引用的被引用的HashSet中添加一个元素
* @param name
*/
public void add(String name) {
stooges.add(name);
}

public boolean isStooge(String name) {
return stooges.contains(name);
}

public void print() {
Iterator<String> iterator = stooges.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next() + ", ");
}
}

public static void main(String[] args) {

ThreeStooges ts = new ThreeStooges();
ts.add("asn");
ts.print();
}
}

输出:

Moe,
asn,
Curly,
Larry,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: