2015-12-14 59 views
0

首先,感謝您的閱讀!我可以從超類對象數組中獲取子類變量嗎?

我做了一個「運動員」,這是「足球運動員」的超級類。 所以我做了一個Sportsman對象的數組,它也包含足球對象,這裏沒有問題(我對繼承的工作原理有一個很好的概念)。

我可以將特定於足球運動員的變量設置爲數組中的對象,但是當我要打印剛剛聲明給該對象的變量時,我無法調用get-methods,因爲該數組是一個Sportsman-array而不是一個足球運動員陣列。

所以這裏是我的問題:我如何從運動員超類數組中打印足球運動員特定變量?

事情要知: 我無法爲子類對象創建單獨的數組。他們必須混合! 雖然在超類對象的數組中放置了一個子類對象,但我明確地將其作爲子類對象。但是,我無法在其上使用子類方法。

主要代碼:

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. 
    */ 
    } 
}}} 

回答

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.. 
    } 
} 
+1

鑄件確實解決了問題!太感謝了! –

相關問題