我有这个代码
public class Student extends Person {
//id represents the student's ID
private int id;
//grade represents the student's grade in the course
private Grade grade;
//constructor allows user to define first and last names, id, and grade of student in demo
public Student(String fName, String lName, int id, Grade grade) {
super(fName, lName);
this.id=id;
this.grade=grade;
}
//get methods for fields
public int getId() {
return id;
}
public Grade getGrade() {
return grade;
}
//toString prints out the string from person class along with id and grade fields in formatted string
public String toString() {
return super.toString()+"'s id is " + id + "." +getGrade();
}
}
还有这段代码。问题是toString 方法使用 passFailGrade getGrade() 返回值而不是位于类中的方法
public class Grade {
private double score;
public Grade(double score) {
this.score=score;
}
public void setScore(double score) {
this.score=score;
}
public double getScore() {
return score;
}
public char getGrade() {
if (getScore()>=90)
return 'A';
else if (getScore()>=80)
return 'B';
else if (getScore()>=70)
return 'C';
else if (getScore()>=60)
return 'D';
else
return 'F';
}
public String toString() {
return "\nThe student recieved a " + getGrade() +
" and had a mark of " + getScore() + ".";
}
}
不确定是否有问题PassFailGrade
:
public class PassFailGrade extends Grade {
public PassFailGrade(double score) {
super(score);
}
public char getGrade() {
if (getScore()>=50)
return 'Y';
else
return 'N';
}
public String toString() {
return "(Y for yes/N for no) The student passed their course ("
+ getGrade()+ ")." + super.toString();
}
}
然后演示类只是在构造函数中定义并打印
public class StudentDemo {
public static void main(String[] args) {
PassFailGrade bo= new PassFailGrade(98);
Student s1 = new Student("bob", "blake", 123, bo);
System.out.println(s1);
}
}
输出:
bob blake 的 id 是 123。(Y 代表是/N 代表否)学生通过了他们的课程 (Y)。该学生得了一个 Y 并且得分为 98.0。