This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
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.
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...
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Oct 30, 2009
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.
Joined: Oct 30, 2009
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.
subject: Inheritance, how to "upgrade" an instance