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.

转载于:https://www.cnblogs.com/JadenLi/p/StaticInnerClass.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值