Java Generics Bounded Wildcard

Introduction

Wildcard arguments can be bounded.

The form is

public void methodName(GenericType<? extends SuperClassName> parameter) {  

In general, to establish an upper bound for a wildcard, use the following type of wildcard expression:

<? extends superclass> 

where superclass is the name of the class that serves as the upper bound.

This is an inclusive clause: the class forming the upper bound is within bounds.

To specify a lower bound for a wildcard by adding a super clause to a wildcard declaration.

Here is its general form:

<? super subclass> 

In this case, only classes that are super classes of subclass are acceptable arguments.

This is an inclusive clause.

class Level1 {
  int x, y;/*from   w  w w. j  a  v a  2 s . c o m*/

  Level1(int a, int b) {
    x = a;
    y = b;
  }
}

class Level2 extends Level1 {
  int z;

  Level2(int a, int b, int c) {
    super(a, b);
    z = c;
  }
}

class Level3 extends Level2 {
  int t;

  Level3(int a, int b, int c, int d) {
    super(a, b, c);
    t = d;
  }
}

class MyArray<T extends Level1> {
  T[] list;

  MyArray(T[] o) {
    list = o;
  }
}

// Demonstrate a bounded wildcard.
public class Main {
  static void showXY(MyArray<?> c) {
    System.out.println("X Y:");
    for (int i = 0; i < c.list.length; i++)
      System.out.println(c.list[i].x + " " + c.list[i].y);
    System.out.println();
  }

  static void showXYZ(MyArray<? extends Level2> c) {
    System.out.println("X Y Z:");
    for (int i = 0; i < c.list.length; i++)
      System.out.println(c.list[i].x + " " + c.list[i].y + " " + c.list[i].z);
    System.out.println();
  }

  static void showAll(MyArray<? extends Level3> c) {
    System.out.println("X Y Z T:");
    for (int i = 0; i < c.list.length; i++)
      System.out.println(c.list[i].x + " " + c.list[i].y + " " + c.list[i].z + " " + c.list[i].t);
    System.out.println();
  }

  public static void main(String args[]) {
    Level1 td[] = { new Level1(0, 0), new Level1(7, 9), new Level1(18, 4), new Level1(-1, -23) };

    MyArray<Level1> list = new MyArray<Level1>(td);

    showXY(list); 

    Level3 fd[] = { new Level3(1, 12, 3, 4), new Level3(6, 8, 1, 8), new Level3(2, 9, 4, 9), new Level3(3, -2, -3, 7) };

    MyArray<Level3> array = new MyArray<Level3>(fd);

    showXY(array);
    showXYZ(array);
    showAll(array);
  }
}



PreviousNext

Related