Is usage of anonymous classes in Java considered bad style or good?

后端 未结 14 1284
Happy的楠姐
Happy的楠姐 2020-12-05 01:58

I know anonymous classes save typing when it comes to implementing Listener and similar stuff. They try to be a replacement for some usages of closures.

But what doe

14条回答
  •  悲哀的现实
    2020-12-05 02:38

    Whether using anonymous class improves or degrades legibility is a matter of taste. The main issue is definitely not here.

    Anonymous classes, like inner classes, carries a reference to the enclosing class, thus making non private things that without it would be. To be short, the this reference of the enclosing class may escape through the inner class. So the answer is: it is a very bad practice to use an inner class if it published itself, since that would automatically publish the enclosing class. for example:

    changeManager.register(new ChangeListener() {
        public void onChange(...) {
           ...
        }});
    

    Here, the anonymous ChangeLstener is passed to the register method of a ChangeManager. Doing so will automatically publish the enclosing class as well.

    This is definitely a bad practice.

提交回复
热议问题