简体   繁体   中英

Accessing subclass method from other class

so I'm making a card game.

I have an arrayList of type player in my main, and I have filled it with a certain type of player (in this case, a good player - good player being a subclass of player with a couple of additional methods)

I may just be brain dead from looking at this for too long however heres my code.

I create 4 good players - again - goodPlayer extends player

ArrayList<Player> players = new ArrayList<>();
    for (int i = 0; i < 4; i++) 
    {
                    goodPlayer gp = new goodPlayer();
                    players.add(gp); 
     }

Then after a couple of methods are called I want to call a method from goodPlayer called count, on each of the goodPlayers in players arrayList

for (Player p : players)
{
            count(p.getHand());
 }

what am I doing wrong as what I currently have is incorrect, unless I make count static and call goodPlayer.count however I do not want the class to act in a static context. Thanks.

Why don't you use type casting? You don't need to make count method a static one to use it. If you are 100% sure that all players in that list will be from GoodPlayer class (by convention, class names start with a capital), then just cast it as

((GoodPlayer) player).count();

If you're not sure if all players will be from the class GoodPlayer, then add a test to avoid a runtime error:

if (player instanceof GoodPlayer) {
     ((GoodPlayer) player).count();
}

A solution would be to add a method on your abstract player class and implement that differently in your derived types of player. For example:

public abstract class Player
{
    public abstract int count();
}

public class GoodPlayer extends Player
{
  public int count()  
  {
    return totalHandsPlayed * 3; //Or something meaningful;
  }

}

This example is showing the you have a base class that asks any inherited classes to implement the methods defined as abstract. (in this case count).

If your players list is always going to hold GoodPlayer objects, then it would be best to have it as aa list of GoodPlayers

Otherwise, the answer given by user mehmetakcay best suits your purpose.

though the information you have provided seems to be little bit abstract but you can do in following manner (using downcasting, though its not recommended):

for(Player p:players){
            GoodPlayer gp=(GoodPlayer)p;
            gp.count();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM