Quantcast
Channel: Why use getters and setters/accessors? - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by Peter D for Why use getters and setters/accessors?

$
0
0

There are many reasons. My favorite one is when you need to change the behavior or regulate what you can set on a variable. For instance, lets say you had a setSpeed(int speed) method. But you want that you can only set a maximum speed of 100. You would do something like:

public void setSpeed(int speed) {  if ( speed > 100 ) {    this.speed = 100;  } else {    this.speed = speed;  }}

Now what if EVERYWHERE in your code you were using the public field and then you realized you need the above requirement? Have fun hunting down every usage of the public field instead of just modifying your setter.

My 2 cents :)


Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>