3D-kreativ
3D-kreativ

Reputation: 9301

Call methods in objects?

I'm a little bit new to objects in Java and I would appreciate some help. I hope I can explain my situation. I have a class, that I call GUI4EX, to handle the the programs GUI. In this class, I also have the main method that creates an instance of GUI4EX:

GUI4EX frame = new GUI4EX();

and also an instance of the class CustomHandler, but this is not done inside the main method:

CustomHandler customHandler = new CustomHandler();

From the code inside GUI4EX I call methods in customHandler like this: CustomHandler.getSomeValue(). How about if I want reach a method in GUI4EX from CustomHandler class? Is this possible and how would I do? Hope my qustions isn't unclear! Thanks!

Upvotes: 0

Views: 88

Answers (2)

anubhava
anubhava

Reputation: 784928

You need to build your class relationship right for that. If I understand you correctly then:

  • GUI4EX has an instance of CustomHandler as a class member
  • But CustomHandler is being constructed with default constructor without passing a GUI4EX reference

Though it will not be a very good design but you can pass a reference of GUI4EX to CustomHandler; either in constructor or in a setter method like this:

class CustomHandler {
   GUI4EX gui;
   // your rest of class members
   public void setGui(GUI4EX gui) {
      this.gui = gui;
   }
   // your rest of methods
}

Then inside some method in class GUI4EX, pass a reference of GUI4EX:

customHandler.setGui ( this );

Upvotes: 1

Yogu
Yogu

Reputation: 9445

You have to understand one important thing for object-orientated programming: Methods belong to objects. You only* can call a method when you know an object whose method to call.

In your example, CustomHandler has to know the specific GUI4EX object to call a method on it. One possibility is to add a parameter to the constructor:

class CustomHandler {   
  private GUI4EX frame;

  public CustomHandler(GUI4EX theFrame) {
    frame = theFrame;
  }
}

Then you can access the field frame for calling a GUI method.

But note that you're going to create a circular relationship. That means that both classes - CustomHandler and GUI4EX depend on each other. This may cause problems and result in bad code design. If you can, try avoiding such dependencies.


* There are also static methods, but they are used less frequently.

Upvotes: 1

Related Questions