本文介绍了匿名与命名内部类?- 最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我们称之为 LineGraph,它呈现一个折线图.我需要对它进行子类化,但是派生类只在一个地方使用,并且与使用它的类耦合.所以我使用的是内部类.

I have a class, let's call it LineGraph, that renders a line graph. I need to subclass it, but the derived class is only used in one place and is coupled to the class that uses it. So I am using an inner class.

我认为有两种方法可以做到这一点:

I see two ways to do this:

匿名内部类

public class Gui {
    LineGraph graph = new LineGraph() {
        // extra functionality here.
    };
}

命名内部类

public class Gui {
    MyLineGraph graph = new MyLineGraph();

    private class MyLineGraph extends LineGraph {
        // extra functionality here.
    }
}

我不喜欢匿名内部类,因为坦率地说,我只是觉得它看起来很丑.但是对于只在一个地方使用的子类,命名内部类是否有点过分?什么是公认的做法?

I am not a fan of anonymous inner classes, because frankly I just think it looks really ugly. But in the case of a subclass that's only used in one place, is a named inner class overkill? What is the accepted practice?

推荐答案

匿名内部类的一个优点是没有人可以在其他任何地方使用它,而命名的内部类可以使用(如果只被创建的类使用)如果将其设为私有).这是一个很小的区别,但这确实意味着您可以保护内部类不被其他地方意外使用.

One advantage of anonymous inner classes is that no one can ever use it anywhere else, whereas a named inner class can be used (if only by the class that created it if made private). It's a small distinction, but it does mean that you can protect an inner class from being accidentally used elsewhere.

此外,使用匿名内部类可以让任何阅读您代码的人抬头——这个类只在此处使用,在其他任何地方都没有使用."如果您看到一个命名的内部类,有人可能会认为它会在类中的多个地方使用.

Also, using the anonymous inner class gives anyone reading your code a head's up - "this class is being used just here and nowhere else." If you see a named inner class, someone might think it'd be used in multiple places in the class.

它们非常相似,所以这两点都不会改变游戏规则.我只是认为,如果您一次性使用匿名内部类,并在类中多次使用时使用命名内部类,这有助于清晰.

They are very similar, so neither point is a game-changer. I just think it helps for clarity if you use anonymous inner classes for one-offs, and named inner classes when it's used multiple times within the class.

这篇关于匿名与命名内部类?- 最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 04:37