当前位置: 代码迷 >> J2SE >> 小疑点请问,多谢
  详细解决方案

小疑点请问,多谢

热度:52   发布时间:2016-04-23 22:35:12.0
小问题请教,谢谢!
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即可。
  相关解决方案