Wildcard in Generics for Java

by kiawin

One thing interesting I learnt today is the scope of Wildcard Generics. Let say both CheckingAccount and SavingsAccount are extended (inherited) from Account:

import com.mybank.domain.*;
import java.util.*;

public class TestCovariance {
  public static void printNames(List  lea) {
    for (int i=0; i < lea.size(); i++) {
      System.out.println(lea.get(i).getName()); //lea only able to access methods from immediate parent class Account only

  public static void main (String[] args) {
    List lc = new ArrayList();
    List ls = new ArrayList();


    List leo = lc; //leo can only access methods from immediate parent class Account only


All the accessible methods from the instantiated wildcard generics in printNames method are limited to the immediate parent class only (in this case we are referring to Account).

This means you can’t use the instatiated lea to access methods from CheckingAccount or SavingsAccount if it was not inherited from their parent class Account.

The wildcard generics relationship are limited between the inherited class with its immediate parent. This differs from polymorphism of object inheritance.