aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes generic code 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 "generic code " Watch "generic code " New topic
Author

generic code

vikram choudhary .
Greenhorn

Joined: Apr 25, 2007
Posts: 7


Above code compiles without warning why?
can any one explain?
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi Vikram,
Actually your confusion runs around last couple of lines of
your code;


class NewClass{
public static void main(String[] args) {

LinkList<String> s=new LinkList<String>();
LinkList<Object> list1;
LinkList<String> list2;
//list1=list2; // this line generates compilation error incompatible types

}
}


Parameterized (generic) assignment doesn't happen in that way.
In one line,
"polymorphism applies to base type not parameterized type."

LinkedList<String> list1 = new ListedList<String>();

Here LinkedList is the base type and <String> is parameterized type.
You can apply the quoted line with the following line:

List<String> list2 new LinkedList<String>();
Here List and LinkedList are base types so no problem. Polymorphism
(parent class/interface type ref variable holding object of subtype/implementing class type object) applies to base type;

You can't write like:
List<Object> list3 = new LinkedList<String>(); //Line #1

under the impression that String IS-A(n) Object. That would be wrong.
Actually these type informations are erased finally. They are only to restrict the programmers so that nothing wrong can be inserted to the List.

After type erasure the Line #1 would become
List list3 = new LinkedList();
[ April 29, 2007: Message edited by: Chandra Bhatt ]

cmbhatt
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Above code compiles without warning why?


Sorry, I cannot read your mind. What warnings are you expecting and on what lines?


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
jQuery in Action, 2nd edition
 
subject: generic code