I know that private instance variables are accessed through their public getters and setters method.
But when I generate constructors with the help of IDE, it initializes instance variables directly instead of initializing them through their setter methods.
Q1. So should I change the IDE generated code for constructors to initialize those instance variables through their setter methods.
Q2. If yes, then why IDE don't generate constructors code in that way?
============================= EDITED =======================================
I use Eclipse and Netbeans IDE
It's a general question. But as asked by @Lords would the answer depends on whether our constructor is public or protected or package private or private?
You should never call a non-final method from a constructor. A 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 which is later overridden by a subclass, you can get strange, unexpected results because the object is not fully initialized when the overridden method is called.
Consider this contrived 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 this program is:
B.getX() = 0
The reason is that B
's number
member is not initialized at the time setX
is called, so its default value of 0
is used.
This article has a more thorough explanation, as does Effective Java.
Constructors are for initialization. Initialize private instance variables directly in the constructor. Methods define an object's behavior. Behavior occurs after instantiation/initialization. Manipulate the state of your instance variables with your setter methods. That's classic OOP thinking and probably why your IDE is generating the code it does.
That depends. If your setters/getters are simply accessing the members you should access them directly. If you also have some code along with it, use setters.
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