1

So I have this:

class A{}
class B extends A {}
class C extends B {
    public String toString(){ return new String("C"); } 
    }
class D extends B {
    public String toString(){ return "D"; } 
    }

And then in main

List<A> list = Arrays.asList(new C(), new D());
        for (A a : list) {
            System.out.println(a.toString());
        }

I can compile this code and it prints: C D but on my friend's computer it won't compile. It has to deal with the Java version I am using ?

  • what is the error..? – Abhishek Feb 01 '15 at 20:11
  • Well i don't know what error my friend got, he just told me that it doesn't compile. I was curious why my code worked on my computer while on my friend's computer didn't. Meanwhile I have found my answer. Thanks! – Ella Pînzaru Feb 01 '15 at 21:19

1 Answers1

5

That's right. You must be compiling on Java 8 while your friend is on Java 7.

In Java 7, the type of of the List returned by

Arrays.asList(new C(), new D());

would be inferred as List<B> and a List<B> cannot be assigned to a List<A>.

In Java 8, with some smarter generics, the compiler would infer a different type for the same expression, List<A>.

You can correct the Java 7 version with an explicit type argument

Arrays.<A>asList(new C(), new D());
Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Thanks! My OOP professor told us in course that it doesn't compile and i was surprised to see that on my computer it compiled. – Ella Pînzaru Feb 01 '15 at 20:27