Get methods return the value of instance variables, for example getWidth() and getHeight() to get the height and width for a Turtle object.
In the previous lesson, we used some set methods with parameters to set the attributes of a turtle to different values, for example yertle.setColor(Color.red); or yertle.setWidth(50); Programmers create get and set methods for each attribute represented as an instance variable in a class to access and modify the value in that variable. The get methods always return back the value of that instance variable, and the set methods modify the value.
When you use a get method, you need to save what it returns in a variable or use the value in some way for example by printing it out. The data type of the variable must match the data type of the return value of the method. You can find out the return type of a method in its documentation. It will be right before the method name, for example int getWidth() means getWidth will return an int (an integer number).
Here are some examples of using get methods for the turtle object yertle.
Turtle yertle = new Turtle(world); int width = yertle.getWidth(); int height = yertle.getHeight(); System.out.println("Yertle's width is: " + width); System.out.println("Yertle's height is: " + height); System.out.println("Yertle's x position is: " + yertle.getXPos() ); System.out.println("Yertle's y position is: " + yertle.getYPos() );
Try the code below that changes the turtle’s width and height. How big or small can you make yertle?
Another common method that returns a value is the toString() method. This method is called automatically to try to convert an object to a String when it is needed, for example in a print statement. In the Turtle class, the toString() method returns a String description of the turtle.
Turtle yertle = new Turtle(world); yertle.setName("yertle"); // set name before you use toString() System.out.println(yertle.toString()); // Or you can just use the object here and it will call toString() automatically! System.out.println(yertle);
Methods that take arguments and return values are like mathematical functions. Given some input, they return a value. For example, a square(x) method would take an argument x and return its square by multiplying it by itself.
The following class has two methods, square and divide. What will the following code print?
You may use this visualization to run through the code.
public class MethodTrace { public int square(int x) { return x*x; } public int divide(int x, int y) { return x/y; } public static void main(String[] args) { MethodTrace traceObj = new MethodTrace(); System.out.println( traceObj.square(2) + traceObj.divide(6,2) ); } }