我可以从超类对象数组中获取子类变量吗?

时间:2015-12-14 17:18:20

标签: java arrays inheritance subclass superclass

首先,感谢阅读!

我创作了一个“运动员”课程,这是“足球运动员”的超级课程。 所以我制作了一个运动员对象数组,其中也包含足球运动员对象,这里没有任何问题(我对继承的工作原理非常了解)。

我可以将足球运动员特定的变量设置为数组中的对象,但是当我想要打印我刚刚向对象声明的变量时,我无法调用get-methods,因为该数组是一个运动员数组,不是足球运动员阵容。

所以这是我的问题:如何从运动员超类阵列打印足球运动员特定变量?

要了解的事项: 我不能为子类对象创建单独的数组。他们必须混在一起! 在将子类对象放入超类对象的数组中时,我明确地将其作为子类对象。但是,我无法在其上使用子类方法。

主要代码:

public class SportApp {
public static void main(String[] args) 
{
Scanner input = new Scanner(System.in);
Sportsman[] sportArr = new Sportsman[10];
for(int count=0 ; count < sportArr.length ; count++)
{   System.out.println("Is the sportsman a footballer?");
    String answer = input.nextLine();
    System.out.println("Last name?");
    String lastName = input.nextLine();
    System.out.println("name?");
    String name = input.nextLine();
    switch (answer){
    case "yes":     System.out.println("Which club does he play in?");
                String club = input.nextLine();
                System.out.println("At what position?");
                String pos = invoer.nextLine();
                sportArr[count]=new Footballer(lastName,name,club,pos);
                break;
    default:    System.out.println("What sport?");
                String sport = input.nextLine();
                sportArr[count]=new Sportsman(lastName,name,sport);
    }
}

System.out.println("All sportsmen that don't play football:");
for(int count=0 ; count < sportArr.length ; count++)
{   if(!(sportArr[count] instanceof Footballer))
    {   System.out.print("name: ");
        sportArr[count].print();}   }

System.out.println("All football players sorted by position:");
//Same as previous print, but with added player position and club!
for(int count=0 ; count < sportArr.length ; count++)
{   if(sportArr[count] instanceof Footballer)
    {
    /*what I've tried:
    *System.out.println("front players:");
    *if(sportArr[count].getPos()=="front")      //the .getPos doesn't work because it wants to invoke it on a Sportsman where getPos doesn't exist
    *{  sportArr[count].print();}       //as the problem above, it doesn't see the object is also a Footballer so it does the Sportsman print()
    *
    *I wanted to do a regular sportArr[count].pos to print the Position but even now it doesn't recognise the object as Footballer, so I can't see pos.
    */
    }
}}}

1 个答案:

答案 0 :(得分:2)

您已在循环中使用instanceof进行了类型检查,如果成功,则表示您拥有Footballer。所以,现在你必须转换对象以获得正确的类型:

if(sportArr[count] instanceof Footballer)
{
    Footballer fb = (Footballer) sportArr[count];

    // Now this should work (note the use of fb, and not using `==` with string literals):
    if(fb.getPos().equals("front")) { 
        // etc..
    }
}
相关问题