Two Laptop Bag
The moose likes Java in General and the fly likes method data passing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "method data passing" Watch "method data passing" New topic

method data passing

Jeremiah Elliott

Joined: Nov 01, 2001
Posts: 17
OK, so here is what I would like to be able to do:
I have two objects first object creates several instances of second object. Every instance of second object needs to be able to call a method of first object.

I have no idea how to word this question in a google search, or what to call the subject of this post.
James Swan
Ranch Hand

Joined: Jun 26, 2001
Posts: 403
You mean something like this?
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
Your choices are:
Create instances of the first class and use those to call the methods of the second class (as James shows you). In this case class2 is "composed" of instances of class1.
You could make it a requirement that you pass an instance or more of class1 when you create an instance of class2. In that case class2 would be an agregate of class1's. You would still use the instance of class1 to invoke the methods of class1.
You could have class2 be a subclass of class1, in which case all instances of class2 will inherit all the methods of class1 that are not overridden in class2. (But you say that you are creating many instances of class1 in class2 so this probably is not what you want).
You could make the methods in class1 static, and use the ClassName.staticMethod() syntax to invoke them. See the Math class for a lovely example of this. No one ever creates any little Math instances (because the constructor is private so you can't), but you can still use all the static methods whenever you want. (again probably not what you are talking about).
You could have class2 be an inner class of class1, in which case the instances of class2 can use all the methods of class1.
[ March 04, 2003: Message edited by: Cindy Glass ]

"JavaRanch, where the deer and the Certified play" - David O'Meara
Jeremiah Elliott

Joined: Nov 01, 2001
Posts: 17
thanks Guys, got it working.
I agree. Here's the link:
subject: method data passing
It's not a secret anymore!