Getters keyword

Hi all,

I don’t understand the purpose of getters and setters in Java.


I don’t understand this task at all and I have looked on w3Schools as well and the solution.

Could someone please explain the purpose of getters & setters as well as how to use them in the code?

Taking Thermostat as an example. There are specified requirements what constructor and temperature getter/setter accept (or expect):

  • constructor accepts Fahrenheit temperature,
  • temperature getter gives temperature in Celsius,
  • temperature setter accepts temperature in Fahrenheit.

However there are no requirements how exactly class needs to keep the actual temperature internally. Due to using getter/setter, internally temperature can be kept either in Celsius or Fahrenheit (or any other temperature unit). And regardless of how that exactly is done temperature getter/setter can always fulfill requirements - getter gives Celsius and setter accepts (expects) Fahrenheit.

This might be a bit abstract in a case that you can change everything the way you want. Imagine there are parts that you cannot change, because somebody expects and depends on fact that temperature to give Celsius.

There are languages where such convention is a bit more formalized and it might be actually expected (otherwise it would be considered as error) that classes will always use getters/setters without even giving ability to be able to see what the internal representation might be.

2 Likes

Note - Java and JavaScript are completely different things!

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.