[英]Java — How to cleanly constuct lists of subclasses from a list of the superclass?
[英]How to access subclasses from a superclass in Java?
我對子類和超類有疑問。 在我正在研究的項目中,我有一個名為“ Team”的超類,還有一些名為“ TeamBlue”,“ TeamRed”的子類。此外,所有這些子類中都包含靜態字段和方法。
我的問題是:如何將任何子類對象(TeamBlue或TeamRed)存儲到“ Team”對象中? 如果這有意義。
這是我要實現的示例:
團隊團隊=新的BlueTeam(); <-將任何顏色團隊存儲到“團隊”對象中
這是我的代碼的簡短版本:
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));
}
這不是面向對象的! 為什么藍隊有一個靜態的球員名單? 為什么公開? 您應該使用getter並覆蓋該方法。
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;
}
}
用法:
Team team = new BlueTeam();
List<String> bluePlayers = team.getPlayers();
您很可能在做類層次結構錯誤。 藍色不是團隊的屬性,顏色是團隊的屬性。 這意味着,不要在Team
為每種可能的顏色子類化,而應該在團隊中擁有一個名為colour
或name
屬性,並在代表藍色或紅色團隊的Team實例中為該屬性分配“藍色”或“紅色”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.