Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

get and set??  RSS feed

 
Jeremy Parsons
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do each of these get and set commands do? I've seen them in a study book, but they fail to mention what they do and are for..
 
Sanjaya Sugiarto
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's what is called encapsulation, an OO feature.

Imagine this:
without encapsulation


Above code has a drawback. You can access the variable grandMasAge from other class without calling checkGrandMasAge for checking the age.



Therefore we need whats called encapsulation getters/setters:



Above code has major benefit: you must set the age through the setGrandMasAge and get the value by calling getGrandMasAge. No way to directly calling the variable grandMasAge.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are no get and set commands in the Java language, so I guess you mean something different. Could you please elaborate? Are you asking about getter and setter *methods*?
 
Michael Foo
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think what he/she means is that the accessor and mutator methods..accessor methods, in your case..the get methods, allows you to get the data while the set methods, the mutator methods allows you to change the data
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Getters and Setters are all about encapsulating data. In Java, we make instance variables private, which makes the data only directly accessible to the class, and we make the data accessible through public setter and getter method.

As we say, in Java, it's not polite to expose our privates.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!