Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Should private instance variables be accessed in constructors through getters and setters method?

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?

like image 200
Yatendra Avatar asked Apr 02 '10 18:04

Yatendra


3 Answers

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.

like image 186
Jason Day Avatar answered Sep 28 '22 02:09

Jason Day


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.

like image 36
Chris Avatar answered Sep 28 '22 01:09

Chris


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.

like image 35
Searles Avatar answered Sep 28 '22 02:09

Searles