面向对象练习题(2)
1.问题描述
(1) 编写老师类:要求有属性“姓名name”,“年龄age”,“职称post”,“基本工资salary”。
(2) 设置4个静态常量:“部门department”值为“baway”,“工资级别levela ,levelb,levelc”初始值分别为1.1,1.2,1.3。
(3) 正确重写Object类方法的toString和equals方法,实现输出教师的基本信息以及对两个基本信息相同(比较的规则:姓名和年龄相同则相等)的老师认为是同一个老师的功能。
2.参考效果图
3.评分规则
(1) 正确定义老师类中属性并正确赋值(5分)
(2) 重写Object类方法,实现输出教师的基本信息代码正确(5分)
(3) 重写Object类方法,实现对两个姓名和年龄相同的老师认为是同一个老师的功能代码正确(备注:要求使用instanceof运算符实现,没有使用此运算符,扣2分)(5分)
(4) 测试类中定义四个教师对象,实例化调用上述方法,最终输出效果如上图(5分)
//编写老师类:要求有属性“姓名name”,“年龄age”,“职称post”,“基本工资salary”。
public class Teacher {
String name;
int age;
String post;//职称
double salary;
//(2) 设置4个静态常量:“部门department”值为“baway”,“工资级别levela ,levelb,levelc”初始值分别为1.1,1.2,1.3。
static final String department = "baway";
static final double levela = 1.1;
public static double levelb = 1.2;
public static double levelc = 1.3;
public Teacher() {
}
public Teacher(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
//(3) 正确重写Object类方法的toString和equals方法,实现输出教师的基本信息以及对两个基本信息相同(比较的规则:姓名和年龄相同则相等)的老师认为是同一个老师的功能。
@Override
public String toString() {
return "姓名是:" + name + "年龄是:" + age + ", 实际工资是:" + salary ;
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (this == obj) {
return true;
}
if (obj instanceof Teacher) {
Teacher teacher2 = (Teacher) obj;
if(this.age==teacher2.age) {
if(this.name.equals(teacher2.name)) {
return true;
}
}
}
return false;
}
}
public class Test1 {
public static void main(String[] args) {
Teacher1 teacher1 = new Teacher1("张老师",36,13000.0);
Teacher1 teacher2 = new Teacher1("刘老师",30,9600.0);
Teacher1 teacher3 = new Teacher1("李老师",29,5280.0);
Teacher1 teacher4 = new Teacher1("李老师",29,5280.0);
System.out.println(teacher1);
System.out.println(teacher2);
System.out.println(teacher3);
boolean b = teacher3.equals(teacher4);
System.out.println("姓名和年龄相同的两个老师是同一个老师结果为:"+b);
}
}