设计一个教师类Teacher,要求: 属性有编号(int no)、姓名(String name)、年龄(int age)、所属学院(String seminary),为这些属性设置相应的get和set方法。 为Teacher类重写equals方法,要求:当两个教师对象的no相同时返回true。 重写Teacher类的toString方法,通过该方法可以返回“no: , name:, age: **, seminary: **”形式的字符串。 输入格式: 两个教师对象的编号,姓名,年龄,学院 输出格式:
时间: 2024-03-15 20:46:51 浏览: 102
以下是实现要求的Java代码:
```
public class Teacher {
private int no;
private String name;
private int age;
private String seminary;
public Teacher(int no, String name, int age, String seminary) {
this.no = no;
this.name = name;
this.age = age;
this.seminary = seminary;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
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;
}
public String getSeminary() {
return seminary;
}
public void setSeminary(String seminary) {
this.seminary = seminary;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Teacher)) {
return false;
}
Teacher teacher = (Teacher) obj;
return this.no == teacher.no;
}
@Override
public String toString() {
return "no: " + no + ", name: " + name + ", age: " + age + ", seminary: " + seminary;
}
}
```
你可以使用以下代码进行测试:
```
Teacher teacher1 = new Teacher(1001, "张三", 35, "计算机科学与技术");
Teacher teacher2 = new Teacher(1002, "李四", 40, "软件工程");
Teacher teacher3 = new Teacher(1001, "王五", 30, "信息管理");
System.out.println(teacher1.equals(teacher2)); // false
System.out.println(teacher1.equals(teacher3)); // true
System.out.println(teacher1); // no: 1001, name: 张三, age: 35, seminary: 计算机科学与技术
System.out.println(teacher2); // no: 1002, name: 李四, age: 40, seminary: 软件工程
System.out.println(teacher3); // no: 1001, name: 王五, age: 30, seminary: 信息管理
```
输入格式:两个教师对象的编号,姓名,年龄,学院
输出格式:no: **, name: **, age: **, seminary: **
阅读全文