Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing functions as parameters?

Status
Not open for further replies.

greedyzebra

Technical User
Sep 5, 2001
140
US
Hi,

I know that in JavaScript you can assign reference to a function and access it's members like any other object, but can this be done with Java? And if so, what would be its functionality?

My situation is this: I'm wanting a function that will call multiple functions. The issue is how to decide which of those functions to call. While it is possible to use a switch statement and call the appropriate function based on a "key" provided as a parameter, there are many possible functions and the number of "cases" would be prohibitive.

If there is some way to reference a function call, then perhaps I could call the function with that reference after the reference has been passed as a parameter.

I'm sure there are other ways to achieve this that I haven't thought of... any suggestions are welcome.

Thanks!
 
>> can this be done with Java?

No.

>> any suggestions are welcome

Java is Object Oriented so first, stop thinking from a “function” standpoint. It sounds like you could use an interface and then several objects that implement that interface to provide different implementations of it.

The interface might declare a single function then you can have multiple classes that implement the interface. Each instance of those classes can be passed to a function that takes the “interface” type as a parameter

Code:
 interface foo{
	public abstract int getInt(String data);
}

class MyFoo implements foo{
	public int getInt(String data){
		return data.length();
	}
}

class UrFoo implements foo{
	public int getInt(String data){
		return data.length() / 2;
	}
}

class TheMain{
	protected static void HereIsAfoo(foo f){
		System.out.println("foo: " + f.getInt("Hello"));
	}
	
	public static void doit(){
		HereIsAfoo( new UrFoo());
		HereIsAfoo( new MyFoo());
	}
}

-pete

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top