【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;
推荐阅读
- 我们的解决思路是使用图引擎来驱动业务逻辑的执行
- VMware ESXI 7.0 手动安装INTEL万兆X550-T2网卡驱动教程
- IDEA提交作业(gitee)
- 自动化集成(Docker容器入门简介)
- day05作业(表示学生信息的类Student)
- DTD(文档类型定义)概述
- 你走对Linux学习之路了吗()
- 使用Tensorflow搭建一个简单的Seq2Seq翻译模型
- 循环神经网络系列Tensorflow中dynamic_rnn