Getters (Observers) & Setters (Transformers)

Transformer is another word for Setter, which is a type of method that changes the internal state of an object.

Observer is another word for Getter, which is a type of method allows you to “observe” the state of the object without changing it. In simpler terms, Getter methods retrieves the value that is tied to the object.

Let’s use an example to show what Getter and Setters do:

So the above example shows a Getter and a Setter. But they aren’t being used. To use them, you have call them up in a Test class, or Main class- whatever class that you are using to run your Java Program. Like this:

java-showing-field-can-be-accessed-if-default

Notice that the x variable field under AnObject class is accessible by the StartPoint class without a setter or getter.java-showing-field-cannot-be-accessed-if-private-setter-must-be-used

But once the x variable field is changed to private, it is no longer directly accessible through obj1 object.adding-getters-and-setters

But if you make getter and setter methods, you can change the value of x associated with the object by using those getter and setter methodsdespite-private-java-modifier-you-can-use-setter-getter

Now in the main class or class that is designed to start from, call the method by first typing the object name, a period, and the method name and new value in the parenthesis. Getters, at least by the one designed in this code, don’t need to be given a value in the parenthesis, but just called.output-because-of-setter-and-getter-java

And you can see that the Java program outputs the new value that is set for the object, 25.

What's Your Opinion?