package com.edu;
class Person {
private int age;
private String name;
public Person() {
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override //toString 为什么要重写?
public String toString() { // Person默认父类为Object
return "name为:" + name + "\n" // Object中含有toString方法,会返回一个字符串
+ "age为:" + age;
}
}
public class day16 {
public static void main(String[] args) {
Person person = new Person();
person.setAge(18);
person.setName("狗蛋");
System.out.println(person);//如果没有toString方法的话就会打印一个地址
// toString可以把地址转换为字符串
}
}
toString为什么要重写
最新推荐文章于 2024-08-24 17:09:16 发布