我想在我的子類中覆蓋超類的方法。但是不管我對我的程序做了什麼改變。它仍然表明由超類的方法進行的結果。那麼,我的代碼有什麼問題?無法在子類中覆蓋超類的方法
我想重寫getChildAge方法和getGreeting方法。它應該在覆蓋後顯示14(如果設置爲12),這只是報告實際年齡加2。對於getGreeting方法,它應該顯示「我是最好的」。不管什麼參數傳遞給getGreeting方法。
這裏是我的代碼:
public class SchoolKid
{
private String childName;
private int childAge;
private String childTeacher;
private String greeting;
//Constructor sets the childName,age,childTeacher and greeting.
public SchoolKid(String childN,int a,String childT,String g)
{
childName = childN;
childAge = a;
childTeacher = childT;
greeting = g;
}
public void setChildName(String childN)
{
childName = childN;
}
public void setChildAge(int a)
{
childAge = a;
}
public void setChildTeacher(String childT)
{
childTeacher = childT;
}
public void setGreeting(String g)
{
greeting = g;
}
public String getChildName()
{
return childName;
}
public int getChildAge()
{
return childAge;
}
public String getChildTeacher()
{
return childTeacher;
}
public String getGreeting()
{
return greeting;
}
}
public class ExaggeratingKid extends SchoolKid
{
private int childAge;
private String greeting;
//Constructor sets the child name,age,childTeacher and greeting.
public ExaggeratingKid(String childNAME,int childAGE,
String childTEACHER,String GREETING)
{
super(childNAME,childAGE,childTEACHER,GREETING);
}
public void setChildAge(int a)
{
childAge = a;
super.setChildAge(childAge+2);
}
public void setGreeting(String g)
{
greeting = "I am the best.";
super.setGreeting("I am the best.");
}
public String toString()
{
String str;
str = "The child's name is "+super.getChildName()+
"\nThe child's age is "+super.getChildAge()+
"\nThe child's teacher is "+super.getChildTeacher()+
"\nThe greeting is: "+super.getGreeting();
return str;
}
}
如果你打電話給超級方法有什麼好處呢?不要在'toString()'中調用'super'方法!調用當前對象的方法,'this'對象。此外,不要給孩子一個問候或childAge字段。 –
我之前曾嘗試過,但會顯示孩子的年齡爲o,問候語爲空。 – zihaow