我正在使用一个程序来帮助我练习编码技能。该程序有以下场景:有一个20名学生的教室,记录了学生的名字、姓氏和年龄。这些学生中有一半参加学校的体育运动。在这里,记录了他们参加过的比赛以及赢得的比赛。 在这个程序中,我有三个类(class):
- runStudents - 具有 main 方法的类
- 学生(字符串姓名、字符串姓氏、整数年龄)- 家长类(class)
- AthleticStudents(字符串名称、字符串姓氏、整数年龄、整数比赛、整数胜利)- 子类别
用户应该能够向对象添加另一场比赛(并获胜)。从提供的代码可以看出,创建了一个数组来存储 20 个 Students 对象。我必须能够访问一个方法来更改数组中的对象,但该方法不在父类(创建对象的类)中。
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();
但不能这样做,因为数组对象是从父类派生的,并且我在子类中声明了该方法。如何将两者联系起来?
最佳答案
我假设您创建了一个父类实例的数组。只需以这种方式转换实例(您最好检查该元素是否是子类的实例):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
关于java - 如果我创建了父类的数组,如何通过数组对象访问子类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57400165/