Fabricio Fabricio - 12 days ago 5
Java Question

How to pass a variable to a inner class

I want to use

canvas
inside
mousePressed
. How can i do that?

public DragManager(Canvas canvas)
{
canvas.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e)
{
canvas.something(); // does not work.
}
});
}

Answer

As many of the guys over here already said you have to make function parameter final.

public DragManager(final Canvas canvas)
{
    canvas.addMouseListener(new MouseAdapter() {
        @Override public void mousePressed(MouseEvent e)
        {
            canvas.something();
        }
    });
}

That means that this variable cannot point to any other object. E.g. you cannot do this inside function:

canvas = SomeOtherCanvas

If you create an object using a local class definition, that object can keep "living" after local variables have been discarded from the stack (after DragManager constructor completion). It has to have a copy of the local values. If you make this parameter final (so it's guaranteed that reference inside constructor wouldn't point to some other place) it's really easy to have a copy: just copy a reference. If there was no such rule you (well, not you personally, but Java language) would need to constantly sync those values and that would be much more complex and slow solution.