Thursday, 14 May 2015

Upper Bound in Java With Example


Upper Bound in Java With Exampl

You can use an upper bounded wildcard to relax the restrictions on a variable. For example, say you want to write a method that works on List<Integer>, List<Double>, and List<Number>; you can achieve this by using an upper bounded wildcard.

To declare an upper-bounded wildcard, use the wildcard character ('?'), followed by the extends keyword, followed by its upper bound. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

To write the method that works on lists of Number and the subtypes of Number, such as Integer, Double, and Float, you would specify List<? extends Number>. The term List<Number> is more restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the latter matches a list of type Number or any of its subclasses.

Consider the following showNumbers method for Example:

 we have used List<? extends Number> which will allow us to pass list of all the Call which is derived from Number all whose super class is Number. so here when you call showNumbers Method then you can pass List of type List<Integer>, List<Float>, List<Double>, List<Number>, etc.. which includes Number class as parent Class.

HelloWorld.java

import java.util.*;
public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        List<Double> li=new ArrayList<Double>();
       
        for (double i = 1; i <= 10; i++) {
               li.add(i);
        }

        HelloWorld.addNumbers(li);
       
     }
    
     public static void showNumbers(List<? extends Number> list) {
     for (int i = 0; i <= list.size()-1; i++) {
         System.out.println(list.get(i));
         }
     }
}