Java - Upper-Bounded Wildcards

Introduction

The Upper-Bounded Wildcard says: the type must be sub type of wildcard.

Syntax

You express the upper bound of a wildcard as

<? extends T>

Example

To add a method to accept two numbers that are wrapped in your Wrapper objects and it will return their sum.

The wrapped objects may be an Integer, Long, Byte, Short, Double, or Float.

static double sum(Wrapper<? extends Number> n1, Wrapper<? extends Number> n2){
        Number num1 = n1.get();
        Number num2 = n2.get();
        double sum = num1.doubleValue() + num2.doubleValue();
        return sum;
}

The following snippet of code inside the method compiles fine:

Number num1 = n1.get();
Number num2 = n2.get();

No matter what you pass for n1 and n2, they will always be assignment-compatible with Number.

Demo

public class Main {
  public static void main(String[] args) {
    Wrapper<Integer> a = new Wrapper<Integer>(1);
    Wrapper<Integer> b = new Wrapper<Integer>(2);
    //from  w  w  w .  j av a2 s.c o  m
    System.out.println(sum(a,b));
    
    
  }
  static double sum(Wrapper<? extends Number> n1, Wrapper<? extends Number> n2){
    Number num1 = n1.get();
    Number num2 = n2.get();
    double sum = num1.doubleValue() + num2.doubleValue();
    return sum;
}
}

class Wrapper<T> {
  private T ref;

  public Wrapper(T ref) {
    this.ref = ref;
  }

  public T get() {
    return ref;
  }

  public void set(T a) {
    this.ref = a;
  }
}

Result

Related Topics

Quiz