When should you use a local class in Java?

前端 未结 1 523
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 16:12

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         


        
相关标签:
1条回答
  • 2020-12-14 16:59

    Local class is something used in some particular method and nowhere else.

    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;
    }
    

    Basically it is just three ints 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.

    0 讨论(0)
提交回复
热议问题