English 中文(简体)
Lower Bounded Wildcards
  • 时间:2024-09-17

Java Generics - Lower Bounded Wildcards


Previous Page Next Page  

The question mark (?), represents the wildcard, stands for unknown type in generics. There may be times when you ll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Integer or its superclasses pke Number.

To declare a lower bounded Wildcard parameter, pst the ?, followed by the super keyword, followed by its lower bound.

Example

Following example illustrates how super is used to specify an lower bound wildcard.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

pubpc class GenericsTester {

   pubpc static void addCat(List<? super Cat> catList) {
      catList.add(new RedCat());
      System.out.println("Cat Added");
   }

   pubpc static void main(String[] args) {
      List<Animal> animalList= new ArrayList<Animal>();
      List<Cat> catList= new ArrayList<Cat>();
      List<RedCat> redCatList= new ArrayList<RedCat>();
      List<Dog> dogList= new ArrayList<Dog>();

      //add pst of super class Animal of Cat class
      addCat(animalList);

      //add pst of Cat class
      addCat(catList);

      //compile time error
      //can not add pst of subclass RedCat of Cat class
      //addCat(redCatList);

      //compile time error
      //can not add pst of subclass Dog of Superclass Animal of Cat class
      //addCat.addMethod(dogList); 
   }
}
class Animal {}

class Cat extends Animal {}

class RedCat extends Cat {}

class Dog extends Animal {}

This will produce the following result −

Cat Added
Cat Added
Advertisements