静态内部类Static Classes

静态内部类就是用static修饰的内部类,因其不依赖于外部类,静态类的实例化不需要通过外部类实例。不同于内部类,静态类中没有保存外部类指针,因此对外部类成员的访问有限制,只能访问外部类的静态成员和方法,但静态类可以声明普通成员变量和方法

当外部类需要使用内部类,而内部类无需外部类资源,并且内部类可以单独创建的时候,一般使用静态类
e.g.

public class Caculate {

    //定义一个pair类来将两个数捆绑
    static class Pair{
        private int first;
        private int second;

        public Pair(int first, int second) {
            this.first = first;
            this.second = second;
        }

        public int getFirst() {
            return first;
        }

        public int getSecond() {
            return second;
        }
    }

    //获取一个int数组中的最大和最小值
    public static Pair getMaxMin(int[] values){
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i:values){
            if (min > i) min = i;
            if (max < i) max = i;
        }
        return new Pair(min,max);
    }

    public static void main(String[] args){
        int[] list = {1,3,5,2,77,23,25};
        Caculate.Pair pair = Caculate.getMaxMin(list);
        System.out.println(pair.getFirst());
        System.out.println(pair.getSecond());
        System.out.println(pair.first);
        System.out.println(pair.second);
    }
}
//例子来源于https://www.cnblogs.com/mfrank/p/8067829.html

这里getMaxMin里需要一次返回两个值,所以用了一个Pair类来将两个数捆绑到一起,而因为这个类只在Caculate类中使用,而且两者并没有依赖关系,所以这里使用静态内部类是最合适的

猜你喜欢

转载自blog.csdn.net/brynjiang/article/details/89631507