Creating an array of objects with derived classes

B

Brayton Larson

Guest
I am attempting to create two players in the program I am writing. The issue is that there are three types of players that can be created but in order to reference them later I want them named as player one and player two. The three classes: "Human", "Computer", and "Karen" are derived classes of "Player". I am wondering how to create an array Player that I can then put player1 and player2 objects in. Is this possible to do?

int playerType = 0;
int highestScore = 0;
Player[] player = new Player[2]; // This is the array of type Player, the master class

Scanner userInput = new Scanner (System.in);

for (int i = 1; i < 3; i++)
{
System.out.println ("Choose a type of player:");
System.out.println ("1: Human");
System.out.println ("2: Computer (Threshold = 20)");
System.out.println ("3. Computer (Custom)");
System.out.print ("? : ");

playerType = Integer.valueOf(userInput.nextLine()); // gets input choice from user


switch (playerType)
{
case 1:
Human player = new Human();
case 2:
Computer player = new Computer();
case 3:
Karen player = new Karen();
}

}


There is another method I tried, using an if statement to make an object playerOne or playerTwo based on what iteration of the for loop we were on (i). Unfortunately it doesn't look like java will compile it because there are multiple declarations of the same variable, even though only one of the declarations should run.

if(playerNumber == 1){
switch (playerType)
{
case 1:
Human playerOne = new Human();
case 2:
Computer playerOne = new Computer();
case 3:
Karen playerOne = new Karen();
}
}

if(playerNumber == 2){
switch (playerType)
{
case 1:
Human playerTwo = new Human();
case 2:
Computer playerTwo = new Computer();
case 3:
Karen playerTwo = new Karen();
}
}

Continue reading...
 
Top