简体   繁体   中英

arrays.aslist adding derived class java

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: CD but on my friend's computer it won't compile. It has to deal with the Java version I am using ?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM