Reputation: 96391
Since i can access private
variables of an inner class directly and ... the only way to access inner
class is via the outer
class .. is there any value in having public accessor/ mutator methods for an inner class?
public class Outer {
Inner i;
Outer() {
i.v = 5;
}
private class Inner {
private int v;
}
}
For the purposes of this question, assume that no lazy instantiation or other data manipulation is needed upon access.
Upvotes: 1
Views: 827
Reputation: 1500175
Well, making the fields non-private would avoid synthetic methods being created to access those private members. In your example, the compiled Outer$Inner
class contains a synthetic method like this:
static int access$002(Outer$Inner, int);
Code:
0: aload_0
1: iload_1
2: dup_x1
3: putfield #1 // Field v:I
6: ireturn
Maybe that will be inlined down to nothing, maybe it won't... but unless there's any reason to force its existence, why not just give v
the default access?
As for using accessor methods rather than using the fields directly... that's more of a matter of taste. You can't prevent the outer class having direct access to the fields, so it's a little like asking whether you should create accessors for private fields within a class.
As mentioned in another answer, using accessors makes it more refactoring-friendly. Is the nested class just an implementation detail which will never need to move? If so, maybe that's fine. I find that if I've got a class like that which is just encapsulating fields with no other behaviour, I make the fields public (within a private class, don't forget) to advertise "Hey, I'm not checking anything here..."
Upvotes: 5
Reputation: 35011
If at some later point you might expose your Inner object thru a function call or in some other way, then yes it is important. It might also be important for synchronization purposes, depending on what's going on in your Inner class
Upvotes: 1