设计完成Human类和Student类,要求能够实现以下功能:
- 两类之间是继承关系;
- 两类中均需有构造函数;
- 重写equals( ), toString( ), hashCode( )方法;
- 测试方法中需体现多态和强制类型转换。
package Human_Student;
import java.util.Objects;
public class Extend {
public static void main(String[] args) {
Student stu1=new Student("xiaoming",12,"man","one");
Student stu2=new Student("xiaoming",12,"man","one");
Student stu3=new Student("xiaowang",22,"woman","ten");
System.out.println("==stu1 is: "+stu1+"\n hashCode is: "+stu1.hashCode());
System.out.println("==stu2 is: "+stu2+"\n hashCode is: "+stu2.hashCode());
System.out.println("==stu3 is: "+stu3+"\n hashCode is: "+stu3.hashCode());
if(stu1.equals(stu2)){
System.out.println("=="+stu1+"\n equals to\n"+stu2+"\n\n");
}
else{
System.out.println("=="+stu1+"\n don't equals to\n"+stu2+"\n\n");
}
if(stu1.equals(stu3)){
System.out.println("=="+stu1+"\n equals to\n"+stu3+"\n\n");
}
else{
System.out.println("=="+stu1+"\n don't equals to\n"+stu3+"\n\n");
}
}
}
class Human{
private String name;
private int age;
private String sex;
public Human(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Human)) return false;
Human human = (Human) o;
return getAge() == human.getAge() && Objects.equals(getName(), human.getName()) && Objects.equals(getSex(), human.getSex());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getAge(), getSex());
}
@Override
public String toString() {
return "Human{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
class Student extends Human{
private String grade;
public Student(String name, int age, String sex, String grade) {
super(name, age, sex);
this.grade = grade;
}
public String getGrade() {
return grade;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
if (!super.equals(o)) return false;
Student student = (Student) o;
return Objects.equals(getGrade(), student.getGrade());
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), getGrade());
}
public void setGrade(String grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student{" +
"name='" + getName() + '\'' +
", age=" + getAge() +
", sex='" + getSex() + '\'' +
"grade='" + grade + '\'' +
'}';
}
}