我有这个代码
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's id is 123.(Y for yes/N for no) The student passed their course (Y). The student recieved a Y and had a mark of 98.0.
最佳答案
您实际上是在覆盖 getGrade()
方法。这是您打算做的事情,但现在您在调用 super.toString()
时遇到了问题 - 它仍然使用您的覆盖方法。
您可以通过以下方式更改 PassFailGrade
中的 toString
来解决此问题:
@Override
public String toString() {
return "(Y for yes/N for no) The student passed their course ("
+ getGrade()+ ")." + "\nThe student recieved a " + super.getGrade() +
" and had a mark of " + getScore() + ".";
}
请注意,我只调用了 super.getGrade()
。这将产生正确的结果。
关于java - 覆盖错误Java,程序不会只读取两种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17519507/