【发布时间】:2019-08-07 18:16:00
【问题描述】:
我正在使用一个程序来帮助我练习我的编码技能。该程序有以下场景:有一个20名学生的教室,其中记录了学生的姓名和年龄。这些学生中有一半参加了学校的体育运动。在这里,记录了他们完成的比赛和赢得的比赛。 在这个程序中,我有三个类:
- runStudents - 带主方法的类
- 学生(字符串姓名、字符串姓氏、整数年龄)- 家长班
- AthleticStudents(字符串名称、字符串姓氏、整数年龄、整数种族、整数胜利)- 子类
用户应该能够向对象添加另一场比赛(并获胜)。如提供的代码所示,创建了一个数组来存储 20 个学生对象。我必须能够访问一个方法来更改数组中的对象,但这个方法不在父类中(创建对象的类。
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
我希望能够做到以下几点:
AthleticStudents[1].anotherRace();
但不能这样做,因为数组对象是从父类派生的,我在子类中声明了该方法。如何将两者联系起来?
【问题讨论】:
-
类名应该是单数形式,并且用PascalCase写。
标签: java class oop methods super