views:

56

answers:

3

In Java, what happens when you reference a private class in a vector from outside the class?

Example:

public class A {
  private class B {}
  public Vector<B> vector = new Vector<B>();

  public A() {
    vector.add(new B());
  }
}

public class C {
  public C() {
    A a = new A();
    a.vector.get(0); // <- What does this return?
  }
}
+1  A: 

It returns the reference to an Object of type A$B.

You will be able to assign it to an Object reference, e.g.

Object o = a.vector.get( 0 );

You can even use reflection to investigate properties of o.

Just a general reminder, please use java.util.ArrayList instead of Vector.

Alexander Pogrebnyak
+1  A: 

It will return an object of type A.B However you cannot do anything with it really because you will not be able to assign it to a variable or call any methods on it. If you do:

System.out.println(a.vector.get(0));

you will get something like:

A$B@42e816
DaveJohnston
If you add a toString() method it will nicely printout whatever toString() returns. However if you call toString() directly it will fail to compile.
Peter Tillemans
+1  A: 

You can try this code:

public static void main(String[] args) {
    A a = new A();
    Object o = a.vector.get(0); // <- What does this return?
    System.out.println(o.getClass());
}

The class is A$B, so it knows that B is an inner class of A.

But you cannot access any of the members of B. For example, if you change class A to this:

public class A {
  private class B {
      public int x;
  }
  public Vector<B> vector = new Vector<B>();

  public A() {
    vector.add(new B());
    vector.get(0).x = 10;
  }
}

You still won't be able to do this:

public static void main(String[] args) {
    A a = new A();
    System.out.println(a.vector.get(0).x); // this won't compile
}

It will say the type A.B is not visible.

dcp