views:

82

answers:

4

What would be the best way to check in an object being passed into a method extended a given class?

Currently i have a method that takes a ByteBuffer of data to send and a 'player' class that i wrote, and queues the data up on the IO server to be sent to the client:

public void send(ButeBuffer toSend, Player player)
{
  // prep the byte buffer for sending, and queue it on the IO server
}

What i would like to be able to do is let the player object passed in be any object that extends the player class. I have done some searches and found something like this:

public void send(ByteBuffer toSend, Player<? extends Player> player)
{   
   // prep the byte buffer for sending, and queue it on the IO server
}

But that is giving me compile errors, and i don't understand exactly whats going on. Would this be the proper way to do this? And if so, could anyone explain what this code is specifically doing and why it isn't working and or link me to an article that explains this in greater detail.

Alternatlly, I suppose i could set it up something like this:

public void send(ByteBuffer toSend, Object player)
{
  // Check that the player extends Player, using instanceof or something 
  // along those lines   

  // Prep the ByteBuffer, and queue the data to send
}

However, that code feels kind of brittle to me, compared to the above code.

Any help is most welcome. Thanks :)

+7  A: 

If I am not mistaken, you can keep the first syntax (expecting a Player object) and it would work with any sub-class of Player. That's polymorphism.

PhiLho
You learn something new every day! Thanks for the info :)
kyeana
+3  A: 

Your current definition of send already accepts any subclass of Player (or implementation, if you later decide to make Player an interface).

Carl
+2  A: 

Currently your method will accept any subclass of Player (if you use the first method). But if you wanted to do this with an interface (to ensure that specific methods are implemented and that you can call them), you can try genericizing the class and do something like this:

public class MyClass<T extends PlayerInterface> {
   public void send(ByteBuffer toSend, T player) {    
      // prep the byte buffer for sending, and queue it on the IO server
   }  
}

But that might be overkill. In this case you might be better off just using an interface as a paramter:

public void send(ByteBuffer toSend, PlayerInterface player) {    
   // prep the byte buffer for sending, and queue it on the IO server
}  
Vivin Paliath
+2  A: 

You first method is fine.

public void send(ButeBuffer toSend, Player player)
{
  // prep the byte buffer for sending, and queue it on the IO server
}

It insures that only objects of type Player (or objects that extend Player) are valid parameters..

I would recommend using interfaces to define what is allowed an what is not allowed as a parameter.

Adrian Regan