Static Inner classes

Background

If you don't need the inner class to access the object of outer class, you can define it as static. Here is an typical example of where you would want to do this. Consider the task of returning the max and minimum values of an array. Of course, you would write two functions to traverse the array. However, it is more efficient to traverse the array once and return two values.
public static void maxmin(int[] intArray)
{
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    for (int i: intArray)
    {
        max = (i > max) ? i : max;
        min = (i < min) ? i : min;
        // return max and min
    }
}

Then you come up with an briliant idea of creating an Pair inner class.

class Pair
{
    private int a;
    private int b;
    public Pair(int a, int b)
    {
        this.a = a;
        this.b = b;
    }

    public int getA() { return a; }
    public int get() { return b; }
}

However, it order to use the Pari class in minmax method, you have to qualified new Pair(min, mx) with the new OuterClass(). qualifier. In this case, there is no need for pair to access OuterClass object. To save you some coding, declare the Pair class as static.

Advantages and disadvantages

In addition to removing boiler-plate code, static inner class is very useful for avoiding name collision betwen to class. To refer to a public static inner class, you have to add the OuterClass. prefix.

How does it work?

Let's look into the class file for pair in more detail. Use javap to decompile the OuterClass$Pair.class:

Compiled from "OuterClass.java"
class blog.StaticInnerClass.StaticInnerClass$Pair {
  public blog.StaticInnerClass.StaticInnerClass$Pair(int, int);
  public int getA();
  public int get();
}

As you can see, that static modifier override the default behaviour of adding a final filed for the OuterClass.

posted @ 2019-06-19 16:43  JadenLi  阅读(102)  评论(0编辑  收藏  举报