Illuminatiiiiii
10/27/2018 - 2:10 AM

Bounded Type Parameters

For Episode 59 of the Java Series:

class Life<A extends Number>{ //A can only be an object of Number or any of it's subclasses

    A[] numberArray;

    public Life(A[] numberArray) {
        this.numberArray = numberArray;
    }

    //our method that returns the sum of all the numbers in the array we provide
    double average(){
        double sum = 0.0;
        for(int i = 0;i < numberArray.length; i++){
            sum += numberArray[i].doubleValue(); //Can't be called without Number extension(or it's subclasses) because it doesnt know you are using number classes
        }
        return sum / numberArray.length;
    }
}
public class Main {

    public static void main(String[] args) {

        Integer[] nums = {1, 5, 4, 2}; //Array of Integers, cannot use ints, cuz it cant autobox int into Integer
        Life<Integer> life1 = new Life<Integer>(nums); //Passes array into new Life Integer Object
        double ttrt = life1.average();
        System.out.println(ttrt); //Prints out our average

        Double[] doubles = {1.3, 13.1, 1.6, 434.2, 2.0};
        Life<Double> life2 = new Life<Double>(doubles);
        System.out.println(life2.average());

        //Following wont work because its a string, obviously you cant average a string, but also String isnt a subclass of Number
//        String[] strings = {"hay", "no", "stop"};
//        Life<String> life3 = new Life<String>(strings);
//        System.out.println(life3.average());

    }
}