Java inline class calling method in parent class

2019-09-16 01:54发布

I'm working on a little Swing application and am in need of some assistance. I have an inline class for a MouseListener and inside one of the methods I would like to call a method in the parent class, however, this is an instance of the MouseListener.

class ParentClass
{
    void ParentMethod()
    {
        //...
        swing_obj.addMouseListener(
            new MouseListener()
            {
                public void mouseClicked(MouseEvent e)
                {
                    //Want to call this.methodX("str"), but
                    //this is the instance of MouseListener
                }
                public void mouseEntered(MouseEvent e){ }
                public void mouseExited(MouseEvent e){ }
                public void mousePressed(MouseEvent e){ }
                public void mouseReleased(MouseEvent e){ }
            }
        );
        //...
    }
    void methodX(String x)
    {
        //...
    }
}

Any assistance would be appreciated.

3条回答
Ridiculous、
2楼-- · 2019-09-16 01:56

Even though this is an instance of the anonymous type, you should still be able to call methodX("str") - just don't prefix it with this.

If you want to be explicit, I think there is some syntax which lets you do it - you can write

ParentClass.this.methodX("str");

but personally I wouldn't bother being explicit unless you really have to (e.g. to disambiguate the call from a method in MouseListener).

查看更多
冷血范
3楼-- · 2019-09-16 01:56

You do not need to do anything but to remove this from the call.

If you still want to use this you have to have the prefix ParentClass. E.g. ParentClass.this.methodX(...)... But that's just ugly and should be used when needed (naming collisions etc).

查看更多
Ridiculous、
4楼-- · 2019-09-16 01:57

As other have stated, simply remove this. and you should be able to call method in the outer class. In those rare cases when the outer class and the nested class have methodS with THE same name and parameter list you call it with OuterClass.this.someMehtod(...);.

For cleaner code when writing anonymous inner classes, I advice you to use adapters. For many of Swings interfaces, there's abstract adapters implementing them and you only override the methods of interest. In this case it would be MouseAdapter:

class ParentClass
{
    void ParentMethod()
    {
        swing_obj.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                someMethodX();
            }
        });
    }

    void methodX(String x)
    {
        //...
    }
}
查看更多
登录 后发表回答