Search code examples
javajbutton

Accessing outer class variable/member in inner class safe practice?


In java for example, I declared and initialized a JButton in outer class and inside the inner class, I decided to make it hidden in some cases, is this a safe programming practice?


Solution

  • The whole purpose of inner classes is that they have access to the outside class that wraps around that inner class.

    So the generic answer is: you are simply making use of a concept that the Java language provides to you. From that point - sure, go for it.

    But beyond that, keep in mind the SOLID principles, like the single responsibility principle. Meaning: when there are good reasons for an inner class to use outer things (to get its "job" done) - then yes, go for it.

    Then: to a certain degree, this is a style question. Inner classes were "famous" in the early years of Java, for example to implement specific listener interfaces. Nowadays they are "less common" - many people prefer "one class per file" and try to avoid nesting classes.

    You see, a inner class is directly coupled to its outer class, so you reduce your ability to re-use that inner part. So you should only use inner classes for things that really conceptually belong "into" your that outer class.

    In other words:

    • don't use a concept just because you can - but because using this concept allows you to "best" implement a specific requirement
    • nobody here can tell you what "works" for your project. Make sure to align with your peers on the style that people agree on, and use that.