Search code examples
javalistprivateinternal

Java: Private Inner Classes being returned to external code


I just started learning Java very recently, coming from a C# background.

When I started using Collections, I noticed that Arrays.asList() returns an ArrayList<T> object.

What I don't understand, is, however, that according to the code listing at 'docjar' (line 2834) labels ArrayList<T> as private.

How can I be using an object that has been explicitly marked as hidden from me? Or (and this is what I suspect), does private have some sort of different meaning to the one I'm assuming?

(Also, I note that that class is marked as static, which also confuses me, but I'll ask that in a separate question)


Edit: Example in C# that throws up a compiler error:

public class PubClass {
        private class Blah {

        }

        public Blah GetBlah() {
            return new Blah();
        }
}

Gives: Inconsistent accessibility: return type 'Namespace.PubClass.Blah' is less accessible than method 'Namespace.PubClass.GetBlah()'


Solution

  • The ArrayList that is returned to you implements List and all of the methods contained in that interface. Since List is public, you know about those methods and can call on them.

    The reason that ArrayList is private is because there is no reason for it to be public: It doesn't provide any additional functionality other than what the List interface provides.

    /edit
    Your example doesn't mimic what's going on here:

    public interface List<T> {
        /** snip */
    }
    
    public class Arrays {
        private static class ArrayList<T> implements List<T> {
            /** snip */
        }
    
        public <T> List<T> asList(T... arr) {
            return new ArrayList<>(arr);
        }
    }
    

    In your example, you are trying to return an instance of a private class which the outside caller has no knowledge of. In the Arrays example, the object being returned is actually a List (take a look at the return type), not a private ArrayList.