CodeNewbie Community 🌱

Cover image for Java Quickie. Nested classes
Tristan
Tristan

Posted on

Java Quickie. Nested classes

Introduction

  • This series is going to be dedicated to the basic understanding of Java. When ever I find myself asking, "How does this work ?". I will create a blog post and put it here. This series will not be in order so feel free to read what ever post you find most relevant. All the resources for this post can be found HERE

Why use nested classes?

  • Well there are 3 main reasons for using a nested class

1) It is a way of logically grouping classes that are only used in one place. If a class is only useful to one other class the it is logical to embed it in that class

2) It increases encapsulation. The nested class still has access to private members of the outer class but remains hidden to the outside world.

3) It can lead to more reliable and maintainable code. Nesting small classes within top-level classes places the code closer to where it is used.

Static nested classes

  • A static nested class is associated with its outer class. Like static methods, a static nested class cannot refer directly to instance variables or method defined in it enclosing class. It can only use them through an object reference.

  • So essentially a nested static class behaves as a normal top-level class that has been nested in another top-level class for packaging convivences.

Conclusion

  • Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.

Top comments (0)