0

Why does Java not support automatic up-casting for template argument types?

For example, the following class will not compile unless the newly created Derived instance will be manually casted to a Base instance:

public class Example implements Iterable<Base> {

    @Override
    public Iterator<Base> iterator() {
        return Arrays.asList(new Derived()).iterator();
    }

    private class Base {
    }

    private class Derived extends Base {

    }
}
Tim
  • 5,521
  • 8
  • 36
  • 69

1 Answers1

3

No need to cast. The problem here is that Arrays.asList(new Derived()) naturally tries to create a List<Derived>, and then calling .iterator() on a List<Derived> naturally gives an Iterator<Derived>, which is not a sub-type of Iterator<Base>, so you get a compilation error.

You can specify that you want a List<Derived>, using Arrays.<Base>asList. This works, because you can certainly put a Derived instance into a List<Base>, and then calling .iterator() on a List<Base> naturally gives an Iterator<Base>.

    class Example implements Iterable<Base> {
        @Override
        public Iterator<Base> iterator() {
            return Arrays.<Base>asList(new Derived()).iterator();
        }
    }
Community
  • 1
  • 1
janos
  • 120,954
  • 29
  • 226
  • 236