File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

Generics Doubt

Eugenio Anton
Greenhorn

Joined: Jun 13, 2013
Posts: 4
I don't understand the answer to this question. The question is if the code below compiles successfully?



My first answer was "yes, of course it compiles, but I don't know if it is overriding or overloading".

But when I qualify my exam I saw that my answer was wrong and the code doesn't compile. I proved it on Eclipse and the compiler said "Name clash: The method say(List<Integer>) of type Child has the same erasure as say(List<String>) of type Parent but does not override it".

I don't know what it means, someone can told me please? Thanks.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

Hi Eugenio. Welcome to the Ranch!

When generics were introduced into Java (version 1.5) they decided to do it in a way that would make it backwards compatible. This was done using type erasure, which means that the generic information is only used an compile time, not an run time.

So in this particular example, at run time these methods both have a signature void say(List list) (which is what it means to say they have "the same erasure"). If it was allowed, it would have to involve overriding. But then you lose type safety.

The compiler has access to the generic types. So it can tell that overriding shouldn't be allowed here. But it's not able to treat this an an overloaded method because it will compile down to the same signature. The only safe approach is to not allow this at all, and raise a compiler error.
Mauro Mazzucco
Ranch Hand

Joined: Apr 26, 2013
Posts: 32

Like Matthew said, Generics only exists for the compiler, the JVM doesnt even know what Generics is, all the Generics code are removed after the compilation wich means your methods would be the same
Eugenio Anton
Greenhorn

Joined: Jun 13, 2013
Posts: 4
Thank you guys. I knew that generics only "work" at compile time and not at runtime. But I never can't imagine that the compiler can anticipate this situation. Thanks a lot.
sahil kumar garg sangrur
Greenhorn

Joined: Jun 05, 2012
Posts: 16
no its does not compile due to concept of bridge method an after the the erasing both the method looks like void say(List list) so same method in subclass is not allowed error of duplicate method...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics Doubt