If I have for example a class along with a helper class to do some of its functionality, does it make sense to make it as an inner class.
public class Foo { private FooHelper helper; // constructor & any other logic public void doSomeThing() { helper.do(); } } public class FooHelper { public void do() { // code } }
In the above case does it make sense to make the FooHelper
as an inner class ? Apology if this sound stupid but I am little confused about the use cases.
Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.
We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable. Additionally, it can access all the members of the outer class, including private data members and methods.
Inner classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private. Nested classes can lead to more readable and maintainable code because it logically group classes in one place only.
Yes, it makes perfect sense to make it an inner class. If no other classes need it, make it private. If it doesn't require exclusive access to the members of the outer class, make it a static nested class because then it will require less memory space.
Check out the recommendation from the official tutorial -
Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.
From JAVA SE Docs
Why Use Nested Classes?
It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.
So Yes, it makes sense to use FooHelper as an inner class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With