Wildcard in Java Generics

he ? (question mark) symbol represents the wildcard element. It means any type. If we write <? extends Number>, it means any child class of Number, e.g., Integer, Float, and double. Now we can call the method of Number class through any child class object.
We can use a wildcard as a type of a parameter, field, return type, or local variable. However, it is not allowed to use a wildcard as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
Let's understand it by the example given below:


  1. import java.util.*;  
  2. abstract class Shape{  
  3. abstract void draw();  
  4. }  
  5. class Rectangle extends Shape{  
  6. void draw(){System.out.println("drawing rectangle");}  
  7. }  
  8. class Circle extends Shape{  
  9. void draw(){System.out.println("drawing circle");}  
  10. }  
  11. class GenericTest{  
  12. //creating a method that accepts only child class of Shape  
  13. public static void drawShapes(List<? extends Shape> lists){  
  14. for(Shape s:lists){  
  15. s.draw();//calling method of Shape class by child class instance  
  16. }  
  17. }  
  18. public static void main(String args[]){  
  19. List<Rectangle> list1=new ArrayList<Rectangle>();  
  20. list1.add(new Rectangle());  
  21.   
  22. List<Circle> list2=new ArrayList<Circle>();  
  23. list2.add(new Circle());  
  24. list2.add(new Circle());  
  25.   
  26. drawShapes(list1);  
  27. drawShapes(list2);  
  28. }}  

Comments

Popular posts from this blog

Codity Test and results

TTD - Test Driven Development for Java Programmers