Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Best approach for setting the values of Instance Variables

 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi ,
Please suggest me as knowing what is the best approach ??

That is to set the values of Instance variables by using an Parameterized constructor as shown below :



Or by explicitly calling the Setter Methods as shown below :




What you suggest , please share your ideas .

Thanks in advnace .
 
Dieter Quickfend
Bartender
Posts: 543
4
Java Netbeans IDE Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd choose the first, given that the second will cause a compiler error.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends. The constructor can be used as a convenient way to set variables, or not prevent other classes from setting the value again via a setter. A problem arises when you have too many instance variables. Using a constructor to instantiate them all would look ugly and difficult to use. Also, using a constructor with parameters forces other classes to pass values when instantiating the class. This can be inconvenient, unless you have different kind of constructors, like a default constructor.
 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you .
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Christophe Verré wrote: A problem arises when you have too many instance variables. Using a constructor to instantiate them all would look ugly and difficult to use.

That can solved by implementing a builder.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wouter Oet wrote:
Christophe Verré wrote: A problem arises when you have too many instance variables. Using a constructor to instantiate them all would look ugly and difficult to use.

That can solved by implementing a builder.

For the reference, that's recommended in Effective Java.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(And don't call super() if you're just extending Object -- there's no need for it, and it's misleading.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic