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都一样
}

posted @   Blululue  阅读(181)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示