问题描述
我刚刚在Java中发现了本地类:
I just discovered local classes in Java:
public final class LocalClassTest
{
public static void main(final String[] args) {
for(int i = 10; i > 0; i--) {
// Local class definition--declaring a new class local to the for-loop
class DecrementingCounter {
private int m_countFrom;
public DecrementingCounter(final int p_countFrom) {
m_countFrom = p_countFrom;
}
public void count() {
for (int c = m_countFrom; c > 0; c--) {
System.out.print(c + " ");
}
System.out.println();
}
}
// Use the local class
DecrementingCounter dc = new DecrementingCounter(i);
dc.count();
}
}
}
我的确发现此评论:,列出了本地课程的一些重大优势匿名内部类。
I did come across this comment: Advantages of Local Classes which listed some great advantages of local classes over anonymous inner classes.
我的问题是,似乎很多情况下这种技术比非匿名内部类有优势。我的意思是:如果你的类只在方法范围内有用,你会使用本地类。但是当你的方法到达它们如此复杂时,你需要开始在它们内部定义自定义类,它们可能已经太复杂了,需要拆分。那么,你的本地课程必须成为一个内部课程,对吗?
My question is, it doesn't seem like there would be many cases where this technique would have advantages over NON-anonymous inner classes. What I mean is: you would use a local class if your class is only useful inside a method's scope. But when your methods get to the point they are so complex you need to start defining custom classes inside of them, they are probably far too complex already, and need to be split up. At which point, your local class would have to become an inner class, right?
当局部课程比内部课程更令人满意的时候有什么例子涉及超复杂的方法(应该避免)?
What are some examples of when local classes are more desirable than inner classes, which don't involved super-complex methods (which should be avoided)?
推荐答案
本地类是某些特定方法中使用的东西而不是其他地方。
Local class is something used in some particular method and nowhere else.
让我举一个例子,我在JPEG解码器/编码器中使用本地类,当我从文件中读取配置时将决定进一步的解码过程。它看起来像这样:
Let me provide an example, I used a local class in my JPEG decoder/encoder, when I read configurations from the file which will determine further decoding process. It looked like this:
class DecodeConfig {
int compId;
int dcTableId;
int acTableId;
}
基本上只有三个 int
s组合在一起。我需要一系列配置,这就是为什么我不能只使用匿名类。如果我用C编码,我会使用一个结构。
Basically it is just three int
s grouped together. I needed an array of configurations, that's why I couldn't use just an anonymous class. If I had been coding in C, I would've used a structure.
我可以用内部类做到这一点,但是所有的解码过程都在一个单独的处理中方法,我不需要在其他地方使用配置。这就是本地课程足够的原因。
I could do this with an inner class, but all the decoding process is handled in a single method and I don't need to use configurations anywhere else. That's why a local class would be sufficient.
这当然是最基本的例子,但它来自现实生活。
This is, of course, the most basic example, but it's from the real life.
这篇关于什么时候应该在Java中使用本地类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!