静态内部类

xiaoxiao2021-03-01  13

       有时候,使用内部类只是为了把一个类隐藏在另一个类的内部,并不需要内部类引用外围类对象。为此,可以将内部类声明为static,以便取消产生的引用。

       如果一个类要被声明为static的,只有一种情况,就是静态内部类。如果在外部类声明为static,程序会编译都不会过。在一番调查后个人总结出了3点关于内部类和静态内部类(俗称:内嵌类)

     1.静态内部类跟静态方法一样,只能访问静态的成员变量和方法,不能访问非静态的方法和属性,但是普通内部类可以访问任意外部类的成员变量和方法

     2.静态内部类可以声明普通成员变量和方法,而普通内部类不能声明static成员变量和方法。

     3.静态内部类可以单独初始化。

     下面是一个使用静态内部类的典型例子。

package staticInnerClass; /** * This program demonstrates the use of static inner classes. */ public class StaticInnerClassTest { public static void main(String[] args) { double[] d = new double[20]; for(int i = 0; i < d.length; i++) d[i] = 100 * Math.random(); ArrayAlg.Pair p = ArrayAlg.minmax(d); System.out.println("min=" + p.getFirst()); System.out.println("max=" + p.getSecond()); } } class ArrayAlg { /** * A pair of floating-point numbers */ public static class Pair { private double first; private double second; /** * Constructs a pair from two floating-point numbers */ public Pair(double f, double s) { first = f; second = s; } /** * Returns the first number of the pair */ public double getFirst() { return first; } /** * Returns the second number of the pair */ public double getSecond() { return second; } } /** * Computes both the minimum and the maximum of an array */ public static Pair minmax(double[] values) { double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; for(double v : values) { if(min > v) min = v; if(max < v) max = v; } return new Pair(min, max); } }

 

转载请注明原文地址: https://www.6miu.com/read-4200221.html

最新回复(0)