(1) 编写一个Student类,包含name和age属性,并完成封装 (2) 提供Student类的无参、有参构造方法。 (3) 在Student类中,重写toString()方法,输出age和name的值。 (4) 在Student类中,重写hashCode()和equals()方法 A、 hashCode()的返回值是name的hash值与age的和。 B、 equals()判断对象的name和age是否相同,相同则返回true不同返回false。 (5) 最后编写一个测试类TestSt
时间: 2024-02-20 22:02:18 浏览: 69
基于python3 类的属性、方法、封装、继承实例讲解
udent,测试Student类的功能。
下面是代码示例:
```
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Name: " + name + ", Age: " + age;
}
@Override
public int hashCode() {
return name.hashCode() + age;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student s = (Student) obj;
return this.name.equals(s.getName()) && this.age == s.getAge();
}
}
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("Tom", 18);
Student s2 = new Student("Tom", 18);
Student s3 = new Student("Jerry", 20);
System.out.println("s1: " + s1.toString());
System.out.println("s2: " + s2.toString());
System.out.println("s3: " + s3.toString());
System.out.println("s1 equals s2: " + s1.equals(s2));
System.out.println("s1 equals s3: " + s1.equals(s3));
System.out.println("s1 hashCode: " + s1.hashCode());
System.out.println("s2 hashCode: " + s2.hashCode());
System.out.println("s3 hashCode: " + s3.hashCode());
}
}
```
输出结果如下:
```
s1: Name: Tom, Age: 18
s2: Name: Tom, Age: 18
s3: Name: Jerry, Age: 20
s1 equals s2: true
s1 equals s3: false
s1 hashCode: 991
s2 hashCode: 991
s3 hashCode: 1021
```
可以看到,重写的toString()方法输出了正确的结果,重写的hashCode()和equals()方法也能正确判断对象是否相等。同时,测试类中也验证了不同对象的hashCode()值不同。
阅读全文