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:
private String myField; //"private" means access to this is restricted public String getMyField() // This is the Getter { return this.myField; // Returns the value that is associated with the myField Object } public void setMyField(String value) // This is the Setter { this.myField = value; // Changes the value of the myField Object to value }
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:
Notice that the x variable field under AnObject class is accessible by the StartPoint class without a setter or getter.
But once the x variable field is changed to private, it is no longer directly accessible through obj1 object.
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 methods
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.
And you can see that the Java program outputs the new value that is set for the object, 25.