File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes an object using it self Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "an object using it self" Watch "an object using it self" New topic

an object using it self

Syamsul Hussin
Ranch Hand

Joined: Feb 09, 2003
Posts: 59
hi, is it possible for an object to to use itself as a parameter of a method. for example:-

constructor of object1 constructs an object2 but since object2 has object1 as one of its field, then object1 has to to send itself as the parameter of object2's constuctor.
is that possible?thanks

----------------------------------<br />SCJP 1.4
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Sure. There is no reason why a class can't have a reference to an instance of the same class. The singleton is a prime example of that. this can be used in any context that calls for a reference to the enclosing class or any of its superclasses. The only caveat is that in a constructor the super constuctor must be called before this can be referenced either implicitly or explicitly, in other words you can't do something like this:

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

There's no problem doing this.

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
I agree. Here's the link:
subject: an object using it self
It's not a secret anymore!