Can a method be a parameter of another method in Java?

Joined
Sep 22, 2008
Messages
1
Reaction score
0
Can an object's method be the parameter when you don't know the object yet?

I'm currently teaching myself OOP and Java via Sam's Teach Yourself OOP in 21 Days.

I'm a tactile learner, so I type everything and try to figure out ways to improve it as I go along.

In the Blackjack game the book has me programming, there is a series of functions that are almost identical that look like this:

protected void notifyChanged()
Iterator<PlayerListener> i = listeners.iterator();
while( i.hasNext() )
{
PlayerListener pl = (PlayerListener) i.next();
pl.playerChanged( this );
}
}

protected void notifyBusted()
{
Iterator<PlayerListener> i = listeners.iterator();
while( i.hasNext() )
{
PlayerListener pl = (PlayerListener) i.next();
pl.playerBusted( this );
}
}

protected void notifyBlackjack()
{
Iterator<PlayerListener> i = listeners.iterator();
while( i.hasNext() )
{
PlayerListener pl = (PlayerListener) i.next();
pl.playerBlackjack( this );
}
}


There are about a dozen of these... seems terribly inefficient.

I'd like to make a single function that would be something like this:


protected void notifyState(NotifyMethod notifyMethod)
{
Iterator<PlayerListener> i = listeners.iterator();
while( i.hasNext() )
{
PlayerListener pl = (PlayerListener) i.next();
pl.notifyMethod( this );
}
}


and then have the above methods as simply:


protected void notifyChanged() {notifyState (playerChanged);}
protected void notifyBusted() {notifyState (playerBusted);}
protected void notifyBlackjack() {notifyState (playerBlackjack);}



Would something like this be possible?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,128
Latest member
ElwoodPhil
Top