Is it bad practice or “dumb” to access methods/fields that are private in the public class from private classes in the same file. In my case I have a method that add components in my GUI to panels(GridBagLayout) so I have made a method for this. However I have three panels so instead of making a addComponent-method in each private class I have the private method addComponent in the public class.
This is a overview of my class:
- RegisterQuestionGUI (public)
- This class has many methods, one of them is a private method named addComponent.
- I also have three private classes that extend JPanel, and all of these classes use the addComponent in exactly the same way.
So back to my question, is this a good/bad way of doing it?
Thanks in advance.
In general, I don’t see an issue with it. Private inner classes are part of the implementation of the outer class, so encapsulation is not broken. OTOH getting rid of duplication is a good thing.
AFAIK this idiom is used many times in the class library (it is there for a reason, after all :-), e.g. when implementing
Iterators in the Collection Framework. Its typical usage tends to have the following common traits:Implementing the interface in a private inner class nicely satisfies both constraints at once, making the logical codependency of the two classes explicit, and encapsulating the implementation class.