#Is it normal to be able to access variables outside of a MouseAdapter/MouseListener?

12 messages · Page 1 of 1 (latest)

ornate tendon
#

I have code in this format:

String test = "test";

objectContainer.addMouseListener(new MouseAdapter() { 
  @Override
  public void mousePressed(MouseEvent event) {
    // Prints "test"
    System.out.println(test);
  }
});

I have read in many examples online that you are unable to access such an outside variable normally. Am I using some sort of bad practice? Is my java version outdated?

winged boltBOT
#

This post has been reserved for your question.

Hey @ornate tendon! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

magic inlet
#

You can read it, but you're not allowed to update it

ornate tendon
#

so then is what I'm doing fine in terms of good/bad practice?

magic inlet
#

There is potentially some danger if it's an object or something you might clean-up elsewhere, but as long as that's not the case it should be fine.

#

You do want the variable you access inside a lambda to be effectively final

ornate tendon
#

would you consider not doing that a case of bad code practice? I don't think I can do that in my case

#

making it final that is

magic inlet
#

You can certainly do that for clarity. I would say it's more of a subjective code quality thing in this case.

There should be a compiler error in case you try to change a variable inside a lambda. You can try to change the value of **test **inside mousePressed and see what happens.

ornate tendon
#

Thank you, this makes a lot more sense now

winged boltBOT