jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics doubt. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics doubt." Watch "Generics doubt." New topic

Generics doubt.

Preetha Vasudevan
Ranch Hand

Joined: Sep 23, 2005
Posts: 33
Hi all
I have a major doubt about generics related to the following code shown below.This code is a question from javabeat.net generics mock exam.
class Basket<E> {
private E element;

public void setElement(E x) {
element = x;

public E getElement() {
return element;

class Fruit {

class Apple extends Fruit {

class Orange extends Fruit {
class GeneTest{
public static void main(String args[]){

Basket<Fruit> basket = new Basket<Fruit>(); // 1
basket.setElement(new Apple()); // 2
Apple apple = basket.getElement(); // 3
The answer to the question is that The line 3 however will cause a runtime error. The result type of the methode getElement of Basket<Fruit> is Fruit. We cannot assign a Fruit to a variable of the type Apple without a cast.
According to me the answer to this code would be that it generates a compiler error at line 2.Because i thought that Basket class is parametarized to contain only Fruits.even though Apple class is a subclass of the Fruit class i thought as generics go against subtyping it would cause an compiler error.
can anyone explain this concept in a better way..

Thank you..
raghava yelamkonda

Joined: Nov 28, 2005
Posts: 10
Only line 3 will give compiletime error
line 2 will not give any error since apple is a sub class of fruit it is passed the instanceof operator
correct me any thing wrong
Thank you
I agree. Here's the link: http://aspose.com/file-tools
subject: Generics doubt.
It's not a secret anymore!