当需要将一个对象输出到显示器时,通常要调用他的toString()方法,将对象的内容转换为字符串.java中的所有类默认都有一个toString()方法
默认情况下 System.out.println(对象名)或者System.out.println(对象名.toString())输出的是此对象的类名和此对象对应内存的首地址 如果想自定义输出信息必须重写toString()方法
注意事项
1.必须被声明为public
2.返回类型为String
3.方法的名称必须为toString,且无参数
4.方法体中不要使用输出方法System.out.println()
例:
package org.tiling.scheduling.examples;
class Patient {
private String name;
private char sex;
private int age;
private float weight;
private boolean allergies;
private int id;
private static int count = 0; // static,用于统计人数
public void print()
// 输出信息 要写void
{
System.out.println("姓名:" + name);// 相当于this.name
System.out.println("序号:" + id);
System.out.println("性别:" + sex);
System.out.println("年龄:" + age);
System.out.println("体重:" + weight);
System.out.println("是否住过院:" + allergies);
System.out.println("当前病人数:" + count);
System.out.println("====================我是分隔线========================");
}
public Patient(String name, char sex, int age, float weight,
boolean allergies) {
this.name = name;
this.sex = sex;
this.age = age;
this.weight = weight;
this.allergies = allergies;
count++;
id = count;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
java.text.DecimalFormat df = new java.text.DecimalFormat("$0.00"); // $可以不加
return ("姓名:" + name + "/n序号:" + id + "/n性别:" + sex + "/n年龄:" + age
+ "/n体重:" + df.format(weight) + "/n是否住过院:" + allergies
+ "/n人数:" + count + "/n=====================我是分隔线=======================");
}
}
public class PatientTester {
public static void main(String args[]) {
Patient PatientA = new Patient("吕振", '男', 21, 111.101f, true); // weight不能写成111.1
// PatientA.print();
// 使用toString方法
System.out.println(PatientA);
Patient PatientB = new Patient("张沛", '男', 22, 101.101f, false);
// PatientB.print();
System.out.println(PatientB.toString());
// 等价于System.out.println(PatientB)
System.out.println("PatientB.getId()=" + PatientB.getId());// 注意!!!!连接符不能用,
PatientB.setName("张沛一");
System.out.println("更改后的病人信息为:");
// PatientB.print();
System.out.println(PatientB);
}
}