我将提供编译器给出的代码和输出,以更好地理解问题。您会发现注册号的值为空...存在问题。 您会在输出中注意到,我获得的注册号为空值...我没有得到它,因为一切似乎都正确,直到不正确为止。
public class Student {
private String regNo;
//Student student = new Test();
public String getRegNo() {
return regNo;
}
public void setRegNo(String number) {
this.regNo = regNo;
}
public void displayRegistrationNumber(){
System.out.println("Registration number: "+ getRegNo());
}
}
-----------------------------------------------------------------'
public class Test extends Student{
private double sub1, sub2;
public double getSub1() {
return sub1;
}
public void setSub1(double sub1) {
this.sub1 = sub1;
}
public double getSub2() {
return sub2;
}
public void setSub2(double sub2) {
this.sub2 = sub2;
}
public void displayScore(){
System.out.printf("Scores: Subject1 = %.0f, Subject2 = %.0f \n",getSub1(), getSub2());
}
}
-----------------------------------------------------------------------
public class Results extends Test {
private double total;
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public void displayTotalScores(){
setTotal(getSub1()+getSub2());
System.out.printf("Total marks: %.0f \n", getTotal());
}
}
---------------------------------------------------------------------
public class Main_method {
public static void main(String[] args){
Results results = new Results();
results.setRegNo("2017-04-06859");
results.setSub1(75.47);
results.setSub2(89);
results.displayRegistrationNumber();
results.displayScore();
results.displayTotalScores();
}
}
这是输出。注意空值
Registration number: null
Scores: Subject1 = 75, Subject2 = 89
Total marks: 164 `
答案 0 :(得分:2)
在这里,您无需为parameter number
分配regNo
,而是为其重新分配了自己的值(最初为null):
public void setRegNo(String number) {
this.regNo = regNo;
}
因此将其更改为:
this.regNo = number;
答案 1 :(得分:0)
这是预期的行为,永远不会使用您传递给public void setRegNo(String number)
的参数。
this.regNo = regNo;
将Student
类(在本例中为null
)中声明的regNo重新分配回调用它的对象。
更改参数或赋值语句
即
public void setRegNo(String regNo)
或
this.regNo = number;