0

So I am making a class that performs an action when a specific event happens. Basically, a variable gets changed to a different value. What I need to do is store a reference to this object from inside the constructor. Here is the code that I am working with to give everyone a better picture:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by iJason on 8/26/2016.
 */
class ClickListener implements ActionListener {
    JLabel label;

    public void actionPerformed(ActionEvent event) {
        label.setText("I was clicked.");
    }

    public ClickListener(JLabel label) {
        this.label = label;
    }
}

So whenever the "actionPerformed" method is called, I want the "label" that is getting passed in to the constructor to actually change. So I need to set a reference to it from the constructor but I am not sure how to do that in Java. Thanks in advance for all the help!

2 Answers2

3

Java uses pass by value. But in the case of objects, the value passed is a reference to the actual object. Which means that the text of the label that is getting passed to the constructor will change. Long story short, your code already does what you want.

uoyilmaz
  • 3,035
  • 14
  • 25
2

Java is always pass by value. It is never pass by reference. Please refer to proper explanation which explains above statement with examples here.

In your example,

public ClickListener(JLabel label) {
    this.label = label;
}

actually, the value( i.e. instance of JLabel) is passed to the constructor method, in which it is assigned to a member variable(i.e reference) of the class ClickListener. Hence the variable ClickListener.label refers to the object being passed. Therefore any modifications done to through ClickListener.label reference variable will be reflected in the original object until it is assigned with new instance of an object.

Community
  • 1
  • 1
pushpavanthar
  • 819
  • 6
  • 20