Renato Dinhani
Renato Dinhani

Reputation: 36726

How does an object pass itself as a parameter?

I have a JFrame that is the main class of the program. I want to pass him itself to another two classes, one that will update some label with statistics and another that will validate a lot of fields.

I done the getters to these fields, but how I do to the JFrame pass itself to these classes to they can do their work?

EDIT: My error, my fault. The first thing I done is the this method. Yes, this solves my problem, but it did not realize that I was making a mistake.

I was doing this: new Statistics().execute(this);
where the right thing is this: new Statistics(this).execute();

Only with all the answers saying the same thing I realized that I was doing a stupid thing. Thanks to all.

Upvotes: 4

Views: 28097

Answers (4)

blank
blank

Reputation: 18170

Just pass a reference to this

public class Other {

   public void doSomething(JFrame jFrame) {
      ...
   }
} 

public class MyFrame extends JFrame {

   Other other = new Other();

   public void method() {
      other.doSomething(this);
   }

}

Upvotes: 17

rk2010
rk2010

Reputation: 3529

did you try using this ?

For example:

other.doSomething(this)

Upvotes: 3

Tyler Treat
Tyler Treat

Reputation: 15008

You can use this to pass itself within a method.

foo(this);

Upvotes: 3

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81704

The pseudo-variable this always points to the current object in an instance method. Just pass this as the argument where you want the reference to go.

Upvotes: 6

Related Questions