I think this might be what you want to do.
public SpecialPlayer(Player player) {
super(player.money);
bar=player.bar;
foo = System.currentTimeMillis();
}
A new specialPlayer
will have the money and bar of the player passed to it.
Alternatively, if you want to set every field to the same as the Player
passed you could try this:
public SpecialPlayer(Player player) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
super(player.money); //Still need to do this
for(Field sfield:player.getClass().getDeclaredFields();){
sfield.setAccessible(true);
sfield.set(this, sfield.get(player));
}
}
This will set all of the fields of the new SpecialPlayer
which are declared in Player
to the value of that field in the player
passed.
To be able to change the state of the original Player
and have it reflected in the new SpecialPlayer
as your update requires you could change all of your references to the original Player
to point to the new SpecialPlayer
.
Player player= new Player(123);
SpecialPlayer special = new SpecialPlayer(player);
player=special;
Another thing to think about, do you really want to make a new SpecialPlayer
with all the same fields as an old Player
, or do you actually just want to make the old Player
special? It might be easier to make the SpecialPlayer
constructor this:
public SpecialPlayer(int money){
super(money);
}
Then for all your players who might later become special you would create like this:
Player player1 = new SpecialPlayer(123);
Player player2 = new SpecialPlayer(345);
And then just cast them to SpecialPlayer
when you want them to be special.
SpecialPlayer special = (SpecialPlayer)player1;
This way you don't need to change your references or create new objects when you make your player special.
You could also add a method in SpecialPlayer
which does what the constructor currently does and call it whenever you want to make that player special:
public void setSpecial(){
foo = System.currentTimeMillis();
}
.
SpecialPlayer special = (SpecialPlayer)player1;
special.setSpecial();
You may also need a flag which could be toggled when a player is setSpecial()
to distinguish if they should use an overridden method or revert to the super method.