Presentation is loading. Please wait.

Presentation is loading. Please wait.

Setter / Mutator methods Methods which accept information and set the value of an object’s property, are called either –setter methods (because they set.

Similar presentations


Presentation on theme: "Setter / Mutator methods Methods which accept information and set the value of an object’s property, are called either –setter methods (because they set."— Presentation transcript:

1 Setter / Mutator methods Methods which accept information and set the value of an object’s property, are called either –setter methods (because they set the value of a property) –mutator methods (because they change – mutate – the value of a property) These methods typically have names that start with “set” 1

2 setColor Both the Ant and the Caterpillar have setColor methods. By calling their setColor methods we can change the color of our Ant and Caterpillar objects. The setColor method requires that a reference to a java.awt.Color object be provided as an argument in the method call. 2

3 java.awt.Color class Instances of the java.awt.Color class represent colors. A color is described by how much of each of the three colors red, green and blue are mixed together. There are some predefined color objects in the java.awt.Color class, such as: java.awt.Color.RED java.awt.Color.BLUE 3

4 Example Suppose a is an Ant, and c is a Caterpillar. Then the following method call sets the color of the Ant object to red: a.setColor(java.awt.Color.RED) Likewise, the following method call sets the color of the Caterpillar object to blue: c.setColor(java.awt.Color.BLUE) 4

5 Getter / Accessor methods Methods which return information, the value of an object’s property, are called either –getter methods (because they get the value of a property) –accessor methods (because they permit access to the value of a property) These methods typically have names that start with “get” 5

6 getColor Both the Ant and the Caterpillar have getColor methods. By calling their getColor methods we can find out the color of our Ant and Caterpillar objects. The getColor method requires no argument in the method call. 6

7 Example Supposing again that a is an Ant. Then the following method call gets a reference to the color of the Ant object: a.getColor() Likewise, the following method call sets the color of the Caterpillar object to blue: c.setColor(java.awt.Color.BLUE) 7

8 Making c and a have the same color c.setColor(a.getColor()) Swapping colors with two variables: java.awt.Color colorOne = a.getColor(); java.awt.Color colorTwo = c.getColor(); c.setColor(colorOne); a.setColor(colorTwo); Exercise: swapping colors with just one variable. 8


Download ppt "Setter / Mutator methods Methods which accept information and set the value of an object’s property, are called either –setter methods (because they set."

Similar presentations


Ads by Google