我想在我的子类中覆盖超类的方法。但是不管我对我的程序做了什么改变。它仍然表明由超类的方法进行的结果。那么,我的代码有什么问题?无法在子类中覆盖超类的方法
我想重写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