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!
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,
CustomHandlerhas to know the specificGUI4EXobject to call a method on it. One possibility is to add a parameter to the constructor:Then you can access the field
framefor calling a GUI method.But note that you’re going to create a circular relationship. That means that both classes –
CustomHandlerandGUI4EXdepend 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.