编写一个学生类: (1)成员变量: 号) 绩) 考生的name(姓名)、id(学 、score(综合成绩)、sports(体育成 (2)构造方法: 无参数 构造 方法 拷贝 构造 方法; >带参数(考生 姓名、考号、综合 成绩、体育 法。 成绩)的构造方法
时间: 2024-01-07 13:05:33 浏览: 102
好的,下面是代码实现:
```
public class Student {
private String name;
private int id;
private double score;
private double sports;
public Student() {
}
public Student(String name, int id, double score, double sports) {
this.name = name;
this.id = id;
this.score = score;
this.sports = sports;
}
public Student(Student s) {
this.name = s.name;
this.id = s.id;
this.score = s.score;
this.sports = s.sports;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public double getSports() {
return sports;
}
public void setSports(double sports) {
this.sports = sports;
}
public double getAverage() {
return (score + sports) / 2;
}
}
```
这里实现了三个构造方法,分别是无参数构造方法、带参数的构造方法和拷贝构造方法。其中,拷贝构造方法接受一个Student对象作为参数,用于复制Student对象的属性。
另外,实现了getAverage方法,用于计算综合成绩的平均值。
使用示例:
```
Student s1 = new Student("Tom", 1, 90.0, 80.0);
System.out.println(s1.getName() + " average score: " + s1.getAverage());
Student s2 = new Student(s1);
s2.setName("Jerry");
System.out.println(s1.getName() + " average score: " + s1.getAverage());
System.out.println(s2.getName() + " average score: " + s2.getAverage());
```
运行结果:
```
Tom average score: 85.0
Tom average score: 85.0
Jerry average score: 85.0
```
可以看到,s2对象通过拷贝构造方法复制了s1对象的属性,但是修改s2的姓名并不会影响s1的姓名。
阅读全文