class
Static inner class example
This is an example of how to use a static inner class. We have set the example as described below:
- We have created a class,
ArAlgothat contains a static inner classP. - Class
Phas two double attributes and their getters. ArAlgoclass also has a static method,P min_max(double[] vals). The method gets a double array and for each value in the array and computes the minimum
and the maximum value in the array.- We create a new double array and fill it with random values, using
random()API method of Math. Then we get a new instance ofPclass, usingmin_max(double[] vals)method ofArAlgoclass, with the double array created above. We use the getters of theArAlgoclass to get the values of the two fields.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
public class StaticInnerClass {
public static void main(String[] args) {
double[] num = new double[20];
for (int i = 0; i < num.length; i++) {
num[i] = 100 * Math.random();
}
ArAlgo.P p = ArAlgo.min_max(num);
System.out.println("min = " + p.getF());
System.out.println("max = " + p.getS());
}
}
class ArAlgo {
/**
* A pair of floating-point numbers
*/
public static class P {
/**
* Constructs a pair from two floating-point numbers
*/
private double f;
private double s;
public P(double a, double b) {
f = a;
s = b;
}
/**
* Returns the first number of the pair
*/
public double getF() {
return f;
}
/**
* Returns the second number of the pair
*/
public double getS() {
return s;
}
}
/**
* Computes both the minimum and the maximum of an array
*/
public static P min_max(double[] vals) {
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (double v : vals) {
if (min > v) {
min = v;
}
if (max < v) {
max = v;
}
}
return new P(min, max);
}
}
Output:
min = 1.5117631236976625
max = 90.86550459529965
This was an example of static inner class in Java.
