Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, Java is pass-by-reference with objects, definitely.</p> <p>But what you're doing is that your <code>Writer</code> assumes that your <code>GUI</code> is written in stone, meaning that it will always have a property called <code>textBox</code>. </p> <p>Just by the look of things, <code>Writer</code> should not be responsible for accessing and manipulating the properties of <code>GUI</code>. If you change what's in your <code>GUI</code>, you will also need to recode the <code>Writer</code> class.</p> <p>You could recode your <code>Writer</code> to merely send a message to the <code>GUI</code> because its responsibility is just to tell <code>GUI</code> what to write, not how to write it. Then leave it upto the <code>GUI</code> to process that message:</p> <pre><code>class GUI { Writer w; void initGUI() { w = new Writer(this); } void ReceiveMessage(string message) { this.textBox.text = message; } } </code></pre> <p>Your <code>Writer</code> class:</p> <pre><code>class Writer { GUI ui; public Write(GUI ui) { this.ui = ui; // Don't send the message in the constructor. } // The program calls this function with whatever text the user enters. public void SendMessage(string message) { ui.ReceiveMessage(message); // Writer no longer depends on ui to have a textbox Element. } } </code></pre> <p>The above code could be improved with an interface. This way, you can pass anything to your writer that needs to know how to receive a message:</p> <pre><code>interface IMessageReceiver { void ReceiveMessage(string message); } </code></pre> <p>Now, your <code>GUI</code> becomes an IMessageReceiver:</p> <pre><code>class GUI implements IMessageReceiver { Writer w; void initGUI() { w = new Writer(this); } public void ReceiveMessage(string message) { this.textBox.text = message; } } </code></pre> <p><code>Writer</code> class now:</p> <pre><code>class Writer { IMessageReceiver receiver; public Write(MessageReceiver receiver) { this.receiver = receiver; // Don't send the message in the constructor. } // The program calls this function with whatever text the user enters. public void SendMessage(string message) { receiver.ReceiveMessage(message); } } </code></pre> <p>The difference here is that <code>Writer</code> will no longer care whether or not it's a <code>GUI</code>. It will take any object as long as it is an <code>IMessageReceiver</code> that knows how to receive messages.</p> <p>If you're not familiar with interfaces, do some reading/research on it. They are extremely handy, if not, vital!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload