Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics" Watch "Generics" New topic
Author

Generics

ujjawal rohra
Ranch Hand

Joined: Mar 20, 2010
Posts: 105
import java.util.*;
class exp{

public static void main(String ar[])
{
List <? extends Number>l1=null;
List<? super Number> l2=null;
l2=l1;
}
}

Why does this code not work?


SCJP 6
Devaka Cooray
ExamLab Creator
Sheriff

Joined: Jul 29, 2008
Posts: 3598
    
  78

Welcome to JavaRanch.
Please UseCodeTags when you post a code at JavaRanch. Please edit your post and add code tags.
Not related to Servlets - Moving to BG...


Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
Devaka Cooray
ExamLab Creator
Sheriff

Joined: Jul 29, 2008
Posts: 3598
    
  78

It is because the generics-scope of l1 and l2 do not match.
Please read GenericsSuperAndExtends to understand the scope of 'extends' and 'super'.
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
Consider what would be if this assignment was legal:

In this code in line 6 we get Object from the list that is declared that can contain only Numbers.
This breaks program with ClassCastException.
To avoid situation like this, compiler prevents assignment in line 04.
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Generics
 
It's not a secret anymore!