How can I update an object in class A from a method in class B without using the return?
for example:
public class A {
//my main class
private javax.swing.JTextField txtField1;
//a text field (txtField1) is initialized in this class and drawn
}
public class B {
public void doSomething(){
//does something and updates the txtField1 in class A
}
}
and once again, I do not wish to use return since my return is already returning another value from the same method.
There are many ways you could achieve this. The simplest would be to pass the object into the method in class B:
Then you can just update
fieldToUpdatedirectly. This is not a great design pattern since it directly exposes control of a variable owned by 1 class to another.Another alternative is to pass the instance of Class A into the method and call public methods on it:
then in class A you’d need to define
This is a little better since class B doesn’t have direct access to the internals of Class A.
An even more encapsulated response (though probably overkill for a case this simple) is to define an Interface and pass an instance of a class that implements the interface to the method in class B:
then in class a:
then the interface:
The advantage of this approach is that it keeps class B completely decoupled from the class A. All it cares about is that it is passed something that knows how to handle the setText method. Again, in this case it is probably overkill, but it is the approach that keeps your classes as decoupled as possible.