Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, reference variables that point to the same object in the memory

I'm developing a GUI program, where I have made classes, that cluster ActionListeners, by functionality. My question is regarding how the JVM handles jButtons, that has the same ActionListener added to them.

First; I am aware that the JVM can save memory, by letting two reference variables that point to an identical string (for instance), point to the same string object in the memory.

public class Example {
    String str1 = "SomeString";
    String str2 = "SomeString";  
}

Now, my question is this: If I have, say, 5 jButtons. All buttons have the same ActionListener added to them. When the program is run, will they have 5 seperate, identical, instaces of the same class added to them? Or will the JVM do something similar (to the above mentioned) ?

  • Thanks in advance :)
like image 264
Daniel Mac Avatar asked Aug 23 '13 18:08

Daniel Mac


2 Answers

Well, it really depends on how you created the ActionListeners. If you did

button1.addActionListener(new ActionListener() {
    ....
});
....
button5.addActionListener(new ActionListener() {
    ....
});

Or

ActionListener al= new ActionListener() {
    ....
};
button1.addActionListener(al);
....
button5.addActionListener(al);

In the first case you, true, have 5 different action listeners. But in the second you have only one. When can you have only one? When it does exactly the same and on the same objects.

like image 167
Mario Rossi Avatar answered Oct 22 '22 00:10

Mario Rossi


It depends.

This will give them the same instance.

ActionListener al = new ActionListener() { ... };
button.addActionListener(al);
button2.addActionListener(al);
...

while this will give them their own.

button.addActionListener(new ActionListener() { ... });
button2.addActionListener(new ActionListener() { ... });
like image 3
sdasdadas Avatar answered Oct 22 '22 01:10

sdasdadas