day12作业(toString()方法和equals()方法)

【day12作业(toString()方法和equals()方法)】少年意气强不羁,虎胁插翼白日飞。这篇文章主要讲述day12作业(toString()方法和equals()方法)相关的知识,希望能为你提供帮助。

//都可以直接Generate生成 //要点1:重写equals()方法,比较内容 【要会手写,体会过程】 //要点2:重写toString()方法,通过toString方法看到这个对象的成员变量的取值

public class Test public static void main(String[] args) Teacher teacher = new Teacher(28, 20000, new Student(21)); System.out.println(teacher.toString()); Teacher teacher1 = new Teacher(28, 20000, new Student(222)); System.out.println(teacher.equals(teacher1)); class Teacher int age; double money; Student s; //构造器 public Teacher(int age, double money, Student s) this.age = age; this.money = money; this.s = s; public Teacher() //toString()方法 @Override public String toString() return "Teacher" + "age=" + age + ", money=" + money + ", s=" + s + ; /*//手写Teacher的equals方法 @Override public boolean equals(Object o) //自反性 if (this == o) return true; //排它性 //getClass 是程序运行中该类唯一的运行时对象,这个是很严格的,必须严格是这个类的对象 if (o == null || this.getClass() != o.getClass()) return false; //表示该obj对象不是当前类的对象//对称性、传递性、一致性 Teacher teacher = (Teacher) o; if (this.age != teacher.age) return false; if (Double.compare(this.money, money) != 0) return false; return s != null ? s.equals(teacher.s) : (teacher.s == null); *///Generate生成 @Override public boolean equals(Object o) if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Teacher teacher = (Teacher) o; if (age != teacher.age) return false; if (Double.compare(teacher.money, money) != 0) return false; return s != null ? s.equals(teacher.s) : teacher.s == null; class Student int age; public Student(int age) this.age = age; public Student() @Override public String toString() return "Student" + "age=" + age + ; @Override public boolean equals(Object o) if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return this.age == student.age;


    推荐阅读