子类覆盖父类的同名方法:public String toString(),该方法没有参数,获取学号姓名,性别,平均分信息
时间: 2024-04-12 15:26:55 浏览: 23
好的,我会在子类中覆盖父类的同名方法 `toString()`,以获取学号、姓名、性别和平均分的信息。以下是示例代码:
```java
public class Student {
protected String studentId;
protected String name;
protected String gender;
protected double averageScore;
// 构造方法
public Student(String studentId, String name, String gender, double averageScore) {
this.studentId = studentId;
this.name = name;
this.gender = gender;
this.averageScore = averageScore;
}
// 父类的 toString() 方法
@Override
public String toString() {
return "Student{" +
"studentId='" + studentId + '\'' +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", averageScore=" + averageScore +
'}';
}
}
public class SubStudent extends Student {
// 构造方法
public SubStudent(String studentId, String name, String gender, double averageScore) {
super(studentId, name, gender, averageScore);
}
// 子类覆盖父类的 toString() 方法
@Override
public String toString() {
return "SubStudent{" +
"studentId='" + studentId + '\'' +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", averageScore=" + averageScore +
'}';
}
}
```
在上面的代码中,我们定义了一个 `Student` 类作为父类,其中包含了学号(`studentId`)、姓名(`name`)、性别(`gender`)和平均分(`averageScore`)等信息。然后,我们在父类中覆盖了 `toString()` 方法,使用字符串拼接的方式返回学生的信息。
接下来,我们定义了一个名为 `SubStudent` 的子类,它继承了 `Student` 类。在子类中,我们同样覆盖了 `toString()` 方法,使用字符串拼接的方式返回子类学生的信息。
通过调用 `toString()` 方法,您可以获取学生的学号、姓名、性别和平均分的信息。希望这个示例对您有帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)