日期:2014-05-20  浏览次数:20648 次

小问题请教,谢谢!
class Student {
public static final Student 小明 = new Student();
public static final Student 小张 = new Student();
public static final Student 小王 = new Student();

private Student() {
//...
}

@Override
public String toString() {
return XXX...
}

public static void main(String[] args) {
System.out.println(Student.小张); // 需要打印结果是“小张”
}
}

请问上述代码的 toString() 方法如何改才能打印出“小张”?
谢谢!

------解决方案--------------------
1).给类增加一个属性:name
2).然后提供一个带参数的构造函数,初始化name。
3).在toString方法中返回name即可。