Kevik
Kevik

Reputation: 9351

passing the self instance of class to another class, from that class, java

how can I pass the instance of the class I am in to another class? what I am trying to do is not working, there must be a better way.

 public class MainExample{

      // constructor
      public MainExample(){

      }

      public static void main(String[] args) {

      MainExample mainCl = // how to get instance of this class?

      NextClass nextCl = new NextClass(mainCl);  // not working, what to pass?           

      }

 }

 public class NextClass {

      MainExample mainEx;

      // constructor
      public NextClass(MainExample me){
      mainEx = me;

      }
 }

<<< EDIT >>>

the reason for this is that I have to pass the current instance of MainExample class to NextClass so that I can attach the observer to the observable. using observer pattern. NextClass will launch multiple threads, one thread for each socket connection. multiple clients. so I have to;

  observable <-- (class instance of class that extends observable class)
  obsever <-- (class instance of class implementing observer)

  using the addObserver method;

  observable.addObserver(observer)

Upvotes: 2

Views: 11816

Answers (3)

Sudhakar
Sudhakar

Reputation: 4873

I hope when you mean MainClass you are referring to class MainExample

if thats the case you dont instance available implicitly by the JVM you have to create one explicitly

MainExample mainCl = new MainExample();
NextClass nextCl = new NextClass(mainCl);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502086

Within the main method, there is no instance of MainClass until you create one, because it's a static method.

Within an instance method you could use this, but in your case you just need to create an instance of MainExample first:

MainExample mainCl = new MainExample();
NextClass nextCl = new NextClass(mainCl);

In an instance method, you would do something like:

public NextClass createNextClass() {
    return new NextClass(this);
}

Upvotes: 2

user2030471
user2030471

Reputation:

Like this: MainExample mainCl = new MainExample();

Your NextClass constructor expects a MainExample reference.

The line NextClass nextCl = new NextClass(mainCl); should compile now.

Upvotes: 5

Related Questions