If you have a private static nested class in Java, is it still recommended to use getters and setters rather than direct field access?
An example. Direct field access:
public class Application {
private List<MyInnerClass> myInnerClassList;
// ...
public void foo() {
MyInnerClass inner = new MyInnerClass();
inner.bar = 50;
myInnerClassList.add(inner);
}
private static class MyInnerClass {
private int bar;
}
}
vs encapsulation:
public class Application {
private List<MyInnerClass> myInnerClassList;
// ...
public void foo() {
MyInnerClass inner = new MyInnerClass();
inner.setBar(50);
myInnerClassList.add(inner);
}
private static class MyInnerClass {
private int bar;
public int getBar() {
return bar;
}
public void setBar(int bar) {
this.bar = bar;
}
}
}
There are several compelling reasons for using nested classes, among them: It is a way of logically grouping classes that are only used in one place. It increases encapsulation. Nested classes can lead to more readable and maintainable code.
- It must extend enclosing class. - It's variables and methods must be static. CORRECT ANSWER : A static inner class does not require an instance of the enclosing class.
A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.
The static inner class can access the static members of the outer class directly. But, to access the instance members of the outer class you need to instantiate the outer class. Nested static class doesn't need a reference of Outer class but a nonstatic nested class or Inner class requires Outer class reference.
Depends but generally I think it is ok. One of the main reasons to use getters and setters is to hide implementation details from the user of the class so you can easily change implementation without affecting the user.
In the case of a private inner class, this is not an issue because you are both the writer and the user of the class, and no one from outside can use it.
If you just use to hold some data together, not having getters and setters will make the code shorter and more readable.
But, if the inner class is bigger and more complicated (which is usually not the case), then you should consider using getters/setters. This will enable you, e.g., to add bounds checking to bar
in your code.
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