package day02.exe;
/**
* 重写toString()和equals()方法
* 一般在自己定义的类中需要重写这两个方法.
* @author Administrator
*
*/
public class Student {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
/* 重写toString()没有特别的原则
* 尽量反映对象的属性.
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString(){
return "name:"+name+",age:"+age;
}
public boolean equals(Object object){
if(object==null){
return false;
}
if(this==object){
return true;
}
if(object instanceof Student){
Student s = (Student)object;
/*
* String类中以重写过equals()方法
* 这里可以直接调用String的toString()方法.
*/
return this.name.equals(s.name) && this.age==s.age;
}
return false;
}
}
package day02.exe;
/**
* 对重写的toString()和equals()方法进行测试
* @author Administrator
*
*/
public class Exe03 {
public static void main(String[] args) {
/*
* 重写过的toString()方法可以输出学生的姓名
* 和年龄信息.
*/
Student s1 = new Student("jack",23);
Student s2 = new Student("jack",23);
Student s3 = new Student("rose",22);
Student s4 = new Student("jack",22);
Student s5 = new Student("rose",23);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println("********************");
/*
* 输出结果如下:
* name:jack,age:23
* name:jack,age:23
* name:rose,age:22
* name:jack,age:22
* name:rose,age:23
* ********************
* s1==s2:true
* s1==s3:false
* s1==s4:false
* s1==s5:false
* 只有当姓名和年龄都相等时才表示
* 是同一个人(实际上姓名和年龄都
* 相等也不能保证是同一个人,这里
* 只是为了演示equals()的重写).
*/
System.out.println("s1==s2:"+s1.equals(s2));
System.out.println("s1==s3:"+s1.equals(s3));
System.out.println("s1==s4:"+s1.equals(s4));
System.out.println("s1==s5:"+s1.equals(s5));
}
}