我想在我的子类中覆盖超类的方法。但无论我对我的程序做了什么改变。它仍然指示超类方法处理的结果。那么,我的代码有什么问题?
我想重写 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;
}
}