//Student2类
/*
* 一般情况下toString方法堆我们来说没有什么用,所以要重写toString方法
* Alt+enter
* Alt+insert
* */
public class Student2 extends Object{
private String name;
private int age;
public Student2() {
super();
}
public Student2(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//重写toString方法
@Override
public String toString() {
return "name = "+name+";"+"age = "+age+";";
}
//通常情况下toString方法不用手动执行,Alt+insert,下面这是源码
public String toString2() {
return "Student2{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//测试类
public class Student2_Test {标签:name,Student2,age,toString,方法,public,String From: https://www.cnblogs.com/Studentcy/p/17467586.html
public static void main(String[] args) {
Student2 s1 = new Student2("陈言",18);
Student2 s2 = new Student2("哈哈",17);
System.out.println(s1.toString());//name = 陈言;age = 18;
System.out.println(s2.toString());//name = 哈哈;age = 17;
//如果直接打印对象的话,那么其实就是在打印该对象的toString方法的返回值
System.out.println("-----------------");
System.out.println(s1);//name = 陈言;age = 18;
System.out.println(s2);//name = 哈哈;age = 17;
}
}