0

Why java wont allow this over-riding? Is there something that I am missing?

class Abc
{
    public void add (List<String> li)
    {

    }

}
public class Test extends Abc {
    public static void main(String args[])
    {

    }

    @Override
    public void add (List<Object> li)
    {

    }

While it does allow the method to override if I remove the

<Object> 

and just write List li in the over riding method which is actually the same as

List<Object>

Also to add, it allows over-riding if both the List in over-ridden and over-riding method have same type.

List<String> - over-ridden method
List<String> - over-riding method
Genius
  • 65
  • 12
  • Because a List is not a List. And because using raw types tells the compiler: do as if generic types didn't exist. http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p, http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – JB Nizet Jan 24 '16 at 15:34
  • You're overriding using generics. – Luiggi Mendoza Jan 24 '16 at 15:34
  • @JBNizet: Can you pls elaborate on "using raw types tells the compiler: do as if generic types didn't exist." – Genius Jan 24 '16 at 15:54
  • @LuiggiMendoza: The question for which you are saying duplicate might sound same but its different. I am asking why it allows 'List li' if not 'List li'. – Genius Jan 24 '16 at 15:58
  • Then this would be the duplicate: http://stackoverflow.com/q/2745265/1065197 – Luiggi Mendoza Jan 24 '16 at 16:11
  • @LuiggiMendoza: I dont think you understand my question. I asked why is java not allowing method with List while it allows List to override. Arent they same. – Genius Jan 25 '16 at 05:49
  • I understood your question and you're still thinking about List when it's about generics at all. I have given you two questions on the topic: one sbout generics and inheritance and another about a similar scenario but in method overriding. Looks likr you haven't read any of them or you still don't understand how they are related to your problem. – Luiggi Mendoza Jan 25 '16 at 13:40

1 Answers1

1

This is a limitation (design flaw? bug?) in how Generics was designed in Java.

Your expectation is reasonable, but the way they decided to implement (and define) Generics made it infeasible.

However, if you think about it, their design is perhaps more reasonable than your expectation: in practical terms, a List<String> probably cannot be directly converted to a List<Object> - something has to create a whole new List, copy the contents over.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Adam
  • 32,900
  • 16
  • 126
  • 153