• Post Reply Bookmark Topic Watch Topic
  • New Topic

handling objects of unknown type  RSS feed

 
jite eghagha
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Below is my scenario:



but i need figth() to handle other weapons, like battleship

then fight() would be:



How do i get one method to handle multiple types: all Objects that fight() accepts have a method: reduce_power_bar()

 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basic design: create a Weapon interface with those methods in, then let Tank, Plane, etc. implement that interface. Or maybe an interface like Exhaustible if you only want the reduce method.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should look into inheritance. Specifically, you should use interfaces. All your objects which can fight might implement an interface called 'Fighter' for example. Fighter defines all the methods necessary for an object that can fight:



Then your Battleship, Tank, and Plane would implement the Fighter interface:


Then your fight() method would take instances of Fighter:


And you could call it like:

 
jite eghagha
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you; solved the problem, and i understand.
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!