In object-oriented programming, methods define the behavior and actions that an object can perform. For example, Turtle objects can go forward or turn left using method calls like yertle.forward() and yertle.turnRight() to change its position. These methods are sometimes called instance methods or object methods because they are called using an instance or object of the class, in this case a specific Turtle object like yertle.
Subsection1.14.1Class Methods vs. Instance Methods
In lessons 1.9 and 1.10, we learned how to call class methods (also called static methods). Class methods are called using the class name followed by the dot (.) operator and the method name, example, Math.sqrt(25); calls the sqrt method in the Math class to find the square root of 25. Class methods use the keyword static in their method signature. They do not access or change the attributes of an object.
In this lesson, we will learn more about instance methods which are always called using an object of the class. They are not static methods. They access and change the attributes of the object they are called on, for example yertle.forward() changes the Turtle object yertleβs position.
The following flowchart shows the difference between calling class (static) methods and instance methods. Static methods are called using the class name, for example, Math.sqrt(25);. Instance methods are called using an object of the class, for example, yertle.forward();. Traditionally, class names are capitalized, and object variables are lowercase.
The method signature defines the methodβs name and the number and types of parameters it takes. In a class definition or in documentation of a library, instance methods are usually defined after the instance variables (attributes) and constructors in a class. For example, see the Student class below. Notice that the methods do not use the keyword static. They are instance methods that are called using an object of the class and can access and change the objectβs attributes.
To use an objectβs method, you must use the object name and the dot (.) operator followed by the method name, for example, yertle.forward(); calls yertleβs forward method to move a turtle object forward 100 pixels. Object methods work with the attributes of the object, such as the direction the turtle is heading or its position.
Methods inside the same class can call each other using just methodName(), but to call instance methods in another class or from a main method, you must first create an object of that class and then call its methods using object.methodName().
method(); is used to call a method within the same class, but object.method(); is necessary if you are calling the method from the main method or from a different class.
Before you call a method from main or from outside of the current class, you must make sure that you have created and initialized an object. However, if you just declare an object reference without setting it to refer to a new object, the value will be null, meaning that it doesnβt reference an object. If you call a method on a variable whose value is null, you will get a NullPointerException error, where a pointer is another name for a reference.
The following flowchart can be used to compare three different ways of calling methods. Class (static) methods are called using the class name. Instance methods are called using an object of the class. If you are calling the instance method from the main method or from another class, you must first create an object of that class and then call its methods using object.methodName(). If you are calling the method from within the same class, you can just call the method using methodName() which will refer to the current object.
In the last lessons, we used simple methods like forward and turnRight to make the turtle draw lines. You may have noticed that forward() and backward() always move the same number of pixels (100 pixels), and turnRight() and turnLeft() always turn at right angles (90 degrees). This is a little limiting. What if we wanted to draw a triangle or the letter A? These require smaller angles to draw diagonal lines and different length lines. Luckily, there are more complex methods in the Turtle class that let you specify the number of pixels to move forward or the number of degrees to turn. These values that you can give to methods to help them do their job are called arguments or parameters. For example, we can give the argument 200 in forward(200) to make the turtle go forward 200 pixels instead of the default of 100 or the argument 30 in turn(30) to make the turtle turn 30 degrees instead of 90 degrees.
When you create your own method, the variables you define for it are called parameters. When you call the method to do its job, you give or pass in arguments to it that are then saved in the parameter variables. So, in the definition of the forward method, it has a parameter variable called pixels, and in the call to forward(200), the argument is the value 200 which will get saved in the parameter variable pixels. You will learn to write your own methods in Unit 3. In this unit, you will learn to call methods that are already written for you.
Here is the Turtle class diagram again that shows some of the variables and methods inherited from the SimpleTurtle class in the class Turtle that are written for you.
Methods are said to be overloaded when there are multiple methods with the same name but a different method signature, where it requires a different number or type of parameters. For example, we have two different forward methods, forward() with no arguments and forward(100) which has an argument that tells it how much to move forward. The arguments given to the method need to correspond to the order and types of the parameters in the method signature.
Can you make yertle draw a square and change the pen color for each side of the square? Try something like: yertle.setColor(Color.red); This uses the Colorβ1β
class in Java which has some colors predefined like red, yellow, blue, magenta, cyan. You can also use more specific methods like setPenColor, setBodyColor, and setShellColor.
Can you draw a triangle? The turnRight() method always does 90 degree turns, but youβll need external angles of 120 degree for an equilateral triangle. Use the turn method which has a parameter for the angle of the turn in degrees. For example, turn(90) is the same as turnRight(). Try drawing a triangle with different colors.
The following code uses a turtle to draw a simple house, but the lines are mixed up. Drag the code blocks to the right and put them in the correct order to first draw a square for the house and then a red triangle for the roof. Click on the βCheck Meβ button to check your solution. You can type this code in the Active Code window above to see it in action.
All the methods on Turtle that weβve discussed so far are void methods with void return type. This means they donβt return anything. Because a void method doesnβt return any value, the only point of calling one is because it does something that can be observed by the user or by other codeβit changes the state of the object or maybe causes something to happen like drawing a line on the screen. Or both. These things they do are sometimes called βeffectsβ.
In contrast, methods with a return type of anything other than void are called non-void methods. These methods return a value that the code calling the method can use. And because methods are called on an object, these methods can be used to return values that tell us things about an objectβs internal state. In well-designed programs, non- void methods typically donβt have effects; they just compute and return a value. To put it another way, void methods do things while non-void methods produce values.
A simple kind of method that returns a value is what is formally called an accessor because it accesses a value in an object. In the real world everyone calls them getters. A getter is a method that takes no arguments and has a non-void return type. In Java they are almost always named something that starts with get, and they usually just return the value of one of the objectβs instance variables. For example, the Turtle class has several getters, getWidth and getHeight which return the width and the height of a Turtle object and getXPos and getYPos which return the x and y values of the Turtleβs position.
Note that when you use a getter, you need to do something with the value it returns. You might assign it to a variable, use it in an expression, or print it out. If you donβt, youβre just getting a value and doing nothing with itβyou might as well not have bothered to call the getter in the first place.
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() );
Note1.14.9.
A common error is forgetting to do something with the value returned from a method. When you call a method that returns a value, you should do something with that value like assigning it to a variable or printing it out.
Try the code below that prints out the turtleβs current position using getXPos() and getYPos(). Can you make it go to position (0,0) or as close to it as possible?
Fix the errors in the code below so that it prints out the area of the space that the turtle occupies by multiplying its width and height. Remember that you have to do something with the values that the get methods return.
We will save a deeper discussion of actually writing getters and other methods until Unit 3, but for the AP progress checks for this unit, you should be able to trace through method calls like the ones below. Notice that the return statement in a method returns the value, and it must match declared return type of the method. The calling method must then do something useful with that value.
public class Rectangle
{
private int width;
private int height;
public Rectangle(int w, int h)
{
width = w;
height = h;
}
public void resize(int amt)
{
width += amt;
}
public int getArea()
{
return width * height;
}
}
Assume that the following code segment appears in a main method.
Given the Rectangle class below, use its constructor to create a 5x10 rectangle, then call its resize method to add 10 to its width, and then print out its area using its getArea method.
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));
}
}
The Turtle class has a method called getDistance(x,y) which will return the turtleβs distance from a point (x,y). Can you find yertleβs distance from the point (0,0)? In the exercise below, add another turtle and make both turtles move. Then find the distance between them. You must use the getXPos and getYPos methods as well as the getDistance method.
Use the getXPos, getYPos, and getDistance(x,y) methods to find yertleβs distance from the point (0,0). Add another turtle, move both turtles to different positions, and find the distance between the two turtles.
This creative challenge is fun to do collaboratively in pairs. Design a house and have the turtle draw it with different colors below. Can you add windows and a door? Come up with your own house design as a team.
It may help to act out the code pretending you are the turtle. Remember that the angles you turn depend on which direction you are facing, and the turtle begins facing up. When planning your coordinates for the house, remember that the turtle starts at the center of the screen (150,150) and the top left corner is (0,0).
A method signature is the method name followed by the parameter list which gives the type and name for each parameter. Note that methods do not have to take any parameters, but you still need the parentheses after the method name.
A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method or constructor before continuing. Once the last statement in the method or constructor has executed or a return statement is executed, the flow of control is returned to the point immediately following the method or constructor call.
Non-void methods are methods that return values. You should do something with the return value, such as assigning it to a variable, using it in an expression, or printing it.
public class Party
{
private int numInvited;
private boolean partyCancelled;
public Party()
{
numInvited = 1;
partyCancelled = false;
}
public void inviteFriend()
{
numInvited++;
}
public void cancelParty()
{
partyCancelled = true;
}
}
Assume that a Party object called myParty has been properly declared and initialized in a class other than Party. Which of the following statements are valid?
public class Cat
{
public void meow()
{
System.out.print("Meow ");
}
public void purr()
{
System.out.print("purr");
}
public void welcomeHome()
{
purr();
meow();
}
/* Constructors not shown */
}
Which of the following code segments, if located in a method in a class other than Cat, will cause the message βMeow purrβ to be printed?
Correct, the Liquid() constructor sets the currentTemp instance variable to 50, and the lowerTemp() method subtracts 10 from it, and getTemp() returns the currentTemp value as a double.
public void splitPizza(int numOfPeople)
{
int slicesPerPerson = 8/numOfPeople;
/* INSERT CODE HERE */
}
public void printSlices(int slices)
{
System.out.println("Each person gets " + slices + " slices each");
}
Which of the following lines would go into /* INSERT CODE HERE
*/ in the method splitPizza in order to call the printSlices method to print the number of slices per person correctly?