Alex Rivera | Logout

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

Asked 2010-04-02T18:40:22.297
10

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?

Edit
Report

1 Answer

0

First of all initialization != setters (at least not always)

But IDEs are just playing nice with once revered JavaBean design pattern Assuming property changes should happen via setters.

So, it is a matter of design. If your classes represent pure value objects, no harm in initializing via = But if your classes have a potential of becoming a JavaBean whose property change is more than just init or assignment, go with set* calls.

answered 2010-04-02T19:29:54.837

Your Answer