Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

handling objects of unknown type

 
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()

 
Marshal
Posts: 69756
277
  • 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.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • 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: 69756
277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done
 
    Bookmark Topic Watch Topic
  • New Topic