Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance, how to "upgrade" an instance

 
Deborah Larsson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am working on a networked game where I have (amongst others ) a Player and a GameHost class.
The GameHost extends the Player class.
Now when the function Player.startnewgame() is done I want the player to become a Gamehost instance. I seem to have lost the insight in how this works.
I can create a new GameHost() but that does not convert the current instance, right? Doesn't the player still exist?
Is the best to

I hope someone can help clarify the idea.
thanks ahead



 
Campbell Ritchie
Sheriff
Posts: 48396
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That doesn't sound possible. Once you create an instance it arises from a particular class, and you can't change the class it arises from.

A few vague ideas, however:

You could replace it with an instance of the new class, particularly if you give it a copy constructor. But maybe "favour composition over inheritance" will come to your aid. Create a wrapper class with a Player instance as a field. When you call the "begin" method, you can replace the Player field with one of its subclasses.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12085
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you create a Player like this

Player currentPlayer = new Player();

then that will forever and always be a Player. but you might be able to do this:



The currentHost reference can change to whichever you need it to...
 
Deborah Larsson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the explanation and help.
I will simply change the code then to create the new Player or object or new GameHost depending on selecting a gamesession or creating one.
On the selection screen it is thus neither but I guess it is not necessary either.
 
Deborah Larsson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, it seems it is not solved.

I can create the Player object when the player choses to join an existing game or create a GameHost when creating a new game.
However after the game is done everyone returns to the loginscreen where one can choose to either again become a host or player.
How should I handle this, since I cannot change the type that they are? Discard those existing instances when they create a new game or join one?

The reason why I have a gamehost subclass of player is since it has extra methods like start and stopgame. Maybe this is a design flaw?

thanks ahead for help.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic