java toString()方法的使用
1.未重写toString()方法时
如使用下System.out.println()方法打印一个集合中的Student(自定义类型)类型的元素
Student类
package collection;
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//先将重写的toString()注释掉
// @Override
// public String toString() {
// return "Student{" +
// "name='" + name + '\'' +
// ", age=" + age +
// '}';
// }
}
Demo主类
package collection;
import java.util.ArrayList;
import java.util.Collection;
/**
* Collection的使用(2)
* @author qky
*/
public class Demo02 {
public static void main(String[] args) {
Collection collection = new ArrayList();
Student s1 = new Student("张三",12);
Student s2 = new Student("李四",15);
collection.add(s1);
collection.add(s2);
System.out.println(collection);//说明。当使用sout输出时,执行System.out.println() 这个方法默认就会调用一个继承自Object 类型对象的toString方法,所以这里collection后面加不加toString都一样
}
2.重写toString()方法时
如使用下System.out.println()方法打印一个集合中的Student(自定义类型)类型的元素
Student类
package collection;
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//将重写的toString()恢复
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Demo主类
package collection;
import java.util.ArrayList;
import java.util.Collection;
/**
* Collection的使用(2)
* @author qky
*/
public class Demo02 {
public static void main(String[] args) {
Collection collection = new ArrayList();
Student s1 = new Student("张三",12);
Student s2 = new Student("李四",15);
collection.add(s1);
collection.add(s2);
System.out.println(collection);//说明。当使用sout输出时,执行System.out.println() 这个方法默认就会调用一个继承自Object 类型对象的toString方法,所以这里collection后面加不加toString都一样
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义