SilverNak
SilverNak

Reputation: 3381

Parameterize Generic Type with private member

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.

Upvotes: 2

Views: 325

Answers (2)

Thomas Kl&#228;ger
Thomas Kl&#228;ger

Reputation: 21630

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

Upvotes: 1

Destroyer
Destroyer

Reputation: 795

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.

Upvotes: 1

Related Questions