直接调用返回的就是字符串内容,官方已经重写好了
    toString的作用:让子类重写,以便返回子类对象的内容
    如果没有重写toString方法默认打出来的就是地址,
    image.png
    image.png
    重写toString方法的快捷方法:右键IDEA选中Generate即可
    image.png
    image.png

    1. package com.itheima.d9_api_object;
    2. /**
    3. * 目标:掌握Object类中toString方法的使用
    4. * toString返回当前对象的地址
    5. */
    6. public class Test {
    7. public static void main(String[] args) {
    8. Student s = new Student("周维",'男',19); // Student类,默认继承了Object类,所以可以使用该类的方法
    9. String rs = s.toString(); // toString返回当前对象的地址
    10. System.out.println(rs); // 这三个打印的都是对象在堆内存中的地址
    11. System.out.println(s.toString()); // toString灰色,可以省略不写
    12. System.out.println(s);
    13. // Student{name='周维', sex=男, age=19}
    14. //按照就近原则,优先调用子类Student本身的
    15. }
    16. }
    1. package com.itheima.d9_api_object;
    2. public class Student { // extends Object 默认继承了Object类
    3. private String name;
    4. private char sex;
    5. private int age;
    6. public Student() {
    7. }
    8. public Student(String name, char sex, int age) {
    9. this.name = name;
    10. this.sex = sex;
    11. this.age = age;
    12. }
    13. @Override
    14. public String toString() {
    15. return "Student{" +
    16. "name='" + name + '\'' +
    17. ", sex=" + sex +
    18. ", age=" + age +
    19. '}';
    20. }
    21. public String getName() {
    22. return name;
    23. }
    24. public void setName(String name) {
    25. this.name = name;
    26. }
    27. public char getSex() {
    28. return sex;
    29. }
    30. public void setSex(char sex) {
    31. this.sex = sex;
    32. }
    33. public int getAge() {
    34. return age;
    35. }
    36. public void setAge(int age) {
    37. this.age = age;
    38. }
    39. }