Parameterize Generic Type with private member

247 Views Asked by At

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.

2

There are 2 best solutions below

0
Destroyer On

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.

0
Thomas Kläger On

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 {}
}