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

why use getter setters in beans

 
anagha patankar
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello ,
We have been using Value objects which we use to get data from db .
these Value objects are taken all the way to the Ui for displaying .

Almost all cases : we have getters and setters ( public ) for private attributes .

My question is :
why do we need getters and setters at all ?

to answer my own question :
for Some attributes it should not be possible to change the value
so we set only getters and not setters .

but then again - the counter arguement being :

To call the getter - I need an instance of the Value Object

If I have an instance of the Value Object - then I can anyways make a change to its attributes .

Please let me know your thoughts .

Thanks ,
-anagha
 
sven studde
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To call the getter - I need an instance of the Value Object

If I have an instance of the Value Object - then I can anyways make a change to its attributes .

Please let me know your thoughts .

My thoughts are that I don't understand your statement. If you have an instance of an object, why can you necessarily make changes to its attributes? See this example:


---------- javac ----------
AATest1.java:15: num has private access in ValueObject
vObj.num = 30;
^
1 error

Output completed (17 sec consumed) - Normal Termination

[ October 04, 2006: Message edited by: sven studde ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume that by Value Object you actually mean a Data Transfer Object.

I agree that Data Transfer Objects don't need getters and setters, public fields are just well. In fact calling them "objects" is kind of a stretch - they are pure data structures, no behaviour at all.

Then again, if you are not writing a distributed system, you probably shouldn't get DTOs from your database layer, but fully fledged domain objects.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic