Consider this class:
public class Activity {
public ArrayList<testInterface> containerListener = new ArrayList<testInterface>();
public void metodoDiProva(int num) {
final int finalNum = num;
containerListener.add(new testInterface() {
@Override
public void metodoDiProva() {
System.out.println(finalNum);
}
});
}
}
Now just look this method:
public void metodoDiProva(int num) {
final int finalNum = num;
containerListener.add(new testInterface() {
@Override
public void metodoDiProva() {
System.out.println(finalNum);
}
});
}
Imagine the metodoDiProva(int num)
is called 2 times, for example:
activityObj.metodoDiProva(10);
activityObj.metodoDiProva(20);
so in the arrayList of the listener there are 2 objects:
The first listener object can use the finalNum variable, the value of this variable is 10.
The second listener object can use the finalNum variable, the value of this variable is 20.
The question is:
In the memory there are 2 different InnerClas or only just 1 ?
No, there is just one inner class; there are two instances of it. When you compile
Activity
, you will see two .class files:Activity.class
andActivity$1.class
, whereActivity$1.class
represents your anonymous inner class.