BlockCoder
BlockCoder

Reputation: 135

How to access subclasses from a superclass in Java?

I have a question about subclasses and superclasses. In a project I'm working on, I have a superclass called "Team" and some subclasses called "TeamBlue","TeamRed"... Also, all of these subclasses have static fields and methods in them.

My question is: how do I store any subclass object (either TeamBlue or TeamRed) into a "Team" object? if this makes sense.

here is an example of what I'm trying to achieve:

Team team = new BlueTeam(); <-- storing any color team into a "team" object

this is a short version of the code I have:

class Team {
    //empty class used for binding all the team classes
}

class BlueTeam extends Team {
    public static List<String> players = new ArrayList<String>();
}

class PlayerData {
    Team playerTeam;
    public PlayerData(Team tm){
        playerTeam = tm;
    }
    playerTeam.players // I want to access any subclass that is stored into this "myTeam" object and access its players list
}


class createData {
    List<PlayerData> data = new ArrayList<PlayerData>();
    // this is what I've tried but I get a null exception
    Team team = new BlueTeam();
    data.add(new PlayerData(team));
}

Upvotes: 0

Views: 385

Answers (2)

Michael
Michael

Reputation: 44090

This is not object-oriented! Why does the blue team have a static list of players? Why is it public? You should use a getter and override the method.

abstract class Team {
    // if there is a sensible default return then use it and the class needn't be abstract
    abstract List<String> getPlayers(); 
}

class BlueTeam extends Team {
    private final List<String> players = new ArrayList<>();

    @Override
    List<String> getPlayers() {
        return players;
    }
}

Usage:

Team team = new BlueTeam();
List<String> bluePlayers = team.getPlayers();

Upvotes: 2

Torben
Torben

Reputation: 3913

You're most likely doing class hierarchy wrong. Blue is not a property of a team, colour is. Meaning that instead of subclassing your Team for every possible colour, you should have a property called colour or name in Team and assign "blue" or "red" to that property in the instance of Team that represents the blue or red team.

Upvotes: 1

Related Questions