问题描述
我有一个类,让我们称之为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.
我看到两种方法:
匿名内部类
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.
}
}
我不是匿名内部类的粉丝,因为坦白地说,我只是认为它看起来真的很丑陋。但是在子类只使用在一个地方的情况下,是一个命名的内部类overkill?
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.
此外,使用匿名内部类给任何人阅读你的代码a头像 - 这个类正在这里和没有其他地方使用。如果你看到一个命名的内部类,有人可能会认为它会在类中的多个地方使用。
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.
这篇关于匿名vs命名的内部类? - 最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!