Java – should private instance variables be accessed in constructors through getter and setter methods?
I know that private instance variables are accessed through their public getter and setter methods
But when I generate a constructor with the help of the IDE, it initializes instance variables directly instead of initializing them through the setter method
Q1. So I should change the code of IDE generated constructors to initialize these instance variables through their setter methods
Q2. If so, why doesn't the IDE generate constructor code in this way?
================================ ===================
>I use eclipse and NetBeans IDE, which is a common problem But according to @ lords' question, the answer depends on whether our constructor is public or protected, private or private?
Solution
You should not call non - Final methods from constructors Class constructor is used to initialize an object, and the object is not in a consistent state until the constructor returns If your constructor calls a non final method that is later overridden by a subclass, you can get strange and unexpected results because the object is not fully initialized when the overridden method is called
Consider this example:
class A { private int x; public A() { setX(2); } public void setX(int x) { this.x = x; } public int getX() { return x; } } class B extends A { private int number = 10; @Override public void setX(int x) { // set x to the value of number: 10 super.setX(number); } } public class Test { public static void main(String[] args) { B b = new B(); // b.getX() should be 10,right? System.out.println("B.getX() = " + b.getX()); } }
The output of the program is:
B.getX() = 0
The reason is that when setx is called, the number member of B is not initialized, so its default value of 0.0 is used
This article has a more thorough explanation of effective Java