2

When creating a class with a generic type, it seems to be impossible to use a private class as type parameter, even when the class is an inner class of the generic type. Consider this code:

import java.util.Iterator;
import test.Test.Type;

public class Test implements Iterable<Type> {

    @Override
    public Iterator<Type> iterator() {return null;}

    static class Type {}

}

The example above compiles, whereas the same example does not compile when Type is private:

import java.util.Iterator;
// ERROR: The type test.Test.Type is not visible
import test.Test.Type;

// ERROR: Type cannot be resolved to a type
public class Test implements Iterable<Type> {

    @Override
    // ERROR: The return type is incompatible with Iterable<Type>.iterator()
    public Iterator<Type> iterator() {return null;}

    private static class Type {}

}

Why is it impossible to use the private class as a type argument for its enclosing class? Even though being private, in my opinion the class Type should be visible within the class Test.

SilverNak
  • 3,283
  • 4
  • 28
  • 44
  • What do you expect the caller of `iterator()` to do with result? It cannot obtain the resulting type, since it is not visible. – Glains Mar 10 '20 at 14:56
  • This is just an example. In my original code, I created a `Collector` with an internal intermediate type - which is only used in the class itself. I just tried to make the example as simple as possible to focus on the behaviour rather than having lots of unrelated lines of code. Therefor I chose the `Iterable` interface – SilverNak Mar 10 '20 at 15:02
  • I was looking at [JLS 6.3](https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.3), but did not find an exact reference, tough i am pretty sure that `T` is out of scope. – Glains Mar 10 '20 at 15:44

2 Answers2

1

I can assume that this is due to the fact that if you make Type privat, you can not get the result of iterator (), since Type is out of sight. I could be wrong.

Destroyer
  • 785
  • 8
  • 20
1

This is because no code outside of your Test class can access Type.

If you restrict the method returning the Iterator to private visibility it will compile:

import java.util.Iterator;

public class Test {

    public void doTest() {
        Iterator<Type> it = iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }

    private Iterator<Type> iterator() {
        return null;
    }

    private static class Type {}
}
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34