Skip to main content
Logo image

Section 1.14 Calling Instance Methods

90 minutes
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.

Subsection 1.14.1 Class 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.
Figure 1.14.1. Calling static vs. instance methods

Subsection 1.14.2 Method Signatures

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.
Figure 1.14.2. A Student class showing instance variables, constructors, and methods

Activity 1.14.1.

Subsection 1.14.3 Method Calls

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().
Figure 1.14.3. Calling instance methods from main() or from other methods inside the same class.

Note 1.14.4.

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.

Activity 1.14.2.

Run the code below to see a NullPointerException. Fix the code by using new Turtle(habitat) to create a new Turtle object before calling its methods.
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.
Figure 1.14.5. Comparing Method Calls to Static and Instance Methods

Subsection 1.14.4 Methods Calls with Arguments

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.

Note 1.14.6.

object.method(arguments); is used to call an object’s method and give it some argument values that it will need to do its job.
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.
Figure 1.14.7. Method signatures with parameters and method calls arguments

Activity 1.14.3.

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.
Figure 1.14.8. Turtle Class Diagram
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.

Activity 1.14.4.

  1. 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 
    docs.oracle.com/en/java/javase/22/docs/api/java.desktop/java/awt/Color.html
    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.
  2. 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.
Try the following mixed up code to draw a simple house made of a square and a triangle roof.

Activity 1.14.5.

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.

Subsection 1.14.5 Methods that Return Values

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.
Here are some examples of using getters on 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() );

Note 1.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.

Activity 1.14.6.

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?

Activity 1.14.7.

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.

Activity 1.14.8.

Consider the following class definition.
public class Circle
{
    private double radius;

    public Circle(double r)
    {
        radius = r;
    }

    public double getArea()
    {
        return 3.14159 * radius * radius;
    }
}
Assume that the following code segment appears in a main method.
Circle c = new Circle(10);
System.out.println(c.getArea());
What is printed as a result of executing the code segment? (If you get stuck, try this visualization
 2 
https://pythontutor.com/visualize.html#code=public%20class%20Circle%0A%7B%0A%20%20%20%20private%20double%20radius%3B%0A%0A%20%20%20%20public%20Circle%28double%20r%29%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20radius%20%3D%20r%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20public%20double%20getArea%28%29%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20return%203.14159%20*%20radius%20*%20radius%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20public%20static%20void%20main%28String%5B%5D%20args%29%20%7B%0A%20%20%20%20%20%20%20%20Circle%20c%20%3D%20new%20Circle%2810%29%3B%0A%20%20%20%20%20%20%20%20System.out.println%28c.getArea%28%29%29%3B%0A%20%20%20%20%7D%0A%7D&cumulative=false&heapPrimitives=nevernest&mode=edit&origin=opt- frontend.js&py=java&rawInputLstJSON=%5B%5D&textReferences=false
to see this code in action.)
  • First, call the constructor, then call getArea().
  • 314.159
  • Correct! getArea() returns 3.14159 * radius * radius, where radius is set to 10 by the constructor.
  • c.getArea()
  • c.getArea() is a method call, not a value.
  • The code will not compile.
  • The code does compile.
  • 100.0
  • Don’t forget to multiply by 3.14159.

Activity 1.14.9.

Consider the following class definition.
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.
Rectangle r = new Rectangle(10, 15);
r.resize(5);
System.out.println(r.getArea());
What is printed as a result of executing the code segment? (If you get stuck, try this visualization
 3 
https://pythontutor.com/render.html#code=public%20class%20Rectangle%0A%7B%0A%20%20%20%20private%20int%20width%3B%0A%20%20%20%20private%20int%20height%3B%0A%0A%20%20%20%20public%20Rectangle%28int%20w,%20int%20h%29%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20width%20%3D%20w%3B%0A%20%20%20%20%20%20%20%20height%20%3D%20h%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20public%20void%20resize%28%29%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20width%20%2B%3D%205%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20public%20int%20getArea%28%29%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20return%20width%20*%20height%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20public%20static%20void%20main%28String%5B%5D%20args%29%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20Rectangle%20r%20%3D%20new%20Rectangle%2810,%2015%29%3B%0A%20%20%20%20%20%20%20%20r.resize%28%29%3B%0A%20%20%20%20%20%20%20%20System.out.println%28r.getArea%28%29%29%3B%0A%20%20%20%20%7D%0A%7D&cumulative=false&curInstr=20&heapPrimitives=nevernest&mode=display&origin=opt- frontend.js&py=java&rawInputLstJSON=%5B%5D&textReferences=false
to see this code in action.)
  • Note that the method resize() is called before getArea().
  • 150.0
  • Note that the method resize() is called before getArea().
  • Correct! resize() increases the width by 5, so the area is 15 * 15 = 225.
  • 255.0
  • Note that getArea() returns an int
  • Note that the constructor initializes width and height.
Let’s try calling the constructor and methods of this Rectangle class in an active code exercise below.

Activity 1.14.10.

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.

Activity 1.14.11.

What does the following code print out? (If you get stuck, try this visualization
 4 
http://www.pythontutor.com/visualize.html#code=public%20class%20MethodTrace%20%0A%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20public%20int%20square%28int%20x%29%0A%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20x*x%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20public%20int%20divide%28int%20x,%20int%20y%29%0A%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20x/y%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20public%20static%20void%20main%28String%5B%5D%20args%29%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20MethodTrace%20traceObj%20%3D%20new%20MethodTrace%28%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20System.out.println%28%20traceObj.square%282%29%20%2B%20traceObj.divide%286,2%29%20%29%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%7D&cumulative=false&curInstr=16&heapPrimitives=nevernest&mode=display&origin=opt- frontend.js&py=java&rawInputLstJSON=%5B%5D&textReferences=false
to see this code in action.)
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));
    }
}
  • Make sure you call both methods and compute the square of 2 and then add the results.
  • Yes, square(2) returns 4 which is added to divide(6,2) which returns 3. The total of 4 + 3 is 7.
  • Make sure you add the results before printing it out.
  • Make sure you square(2) and add the results before printing it out.
  • Does not compile.
  • Try the code in an active code window.
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.

Activity 1.14.12.

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.

Subsection 1.14.6 Coding Challenge : Turtle House

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.
To draw a window, you will need to call penUp and moveTo to walk the turtle into position without drawing, for example:
t.penUp();
t.moveTo(120,200);
t.penDown();
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).

Project 1.14.13.

Draw a Turtle House! Make sure you use forward, turn, penUp, penDown, moveTo methods as well as different colors. Have fun!

Subsection 1.14.7 Summary

  • Instance methods define the behavior and actions that an object can perform.
  • (AP 1.14.A.1) Instance methods are called on objects of the class.
  • (AP 1.14.A.1) The dot operator is used along with the object name to call instance methods, for example object.method();
  • (AP 1.14.A.2) A method call on a null reference will result in a NullPointerException.
  • Some methods take arguments that are placed inside the parentheses object.method(arguments).
  • 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.
  • The method call arguments must match the method signature in number, order, and type.
  • 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.

Subsection 1.14.8 AP Practice

Activity 1.14.14.

Consider the following class definition.
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?
  • myParty.cancelParty();
  • Correct!
  • myParty.inviteFriend(2);
  • The method inviteFriend() does not have any parameters.
  • myParty.endParty();
  • There is no endParty() method in the class Party.
  • myParty.numInvited();
  • There is no numInvited() method in the class Party. It is an instance variable.
  • System.out.println( myParty.cancelParty() );
  • This would cause an error because the void method cancelParty() does not return a String that could be printed.

Activity 1.14.15.

Consider the following class definition.
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?
  • Cat a = new Cat();
    Cat.meow();
    Cat.purr();
    
  • You must use the object a, not the class name Cat, to call these methods.
  • Cat a = new Cat();
    a.welcomeHome();
    
  • This would print β€œpurrMeow β€œ
  • Cat a = new Cat();
    a.meow();
    a.purr();
    
  • Correct!
  • Cat a = new Cat().welcomeHome();
    
  • This would cause a syntax error.
  • Cat a = new Cat();
    a.meow();
    
  • This would just print β€œMeow β€œ.

Activity 1.14.16.

Consider the following class definition.
public class Liquid
{
    private double boilingPoint;
    private double freezingPoint;
    private double currentTemp;

    public Liquid()
    {
        currentTemp = 50;
    }

    public void lowerTemp()
    {
        currentTemp -= 10;
    }

    public double getTemp()
    {
        return currentTemp;
    }
}
Assume that the following code segment appears in a class other than Liquid.
Liquid water = new Liquid();
water.lowerTemp();
System.out.println(water.getTemp());
What is printed as a result of executing the code segment? (If you get stuck, try this visualization
 5 
https://pythontutor.com/render.html#code=public%20class%20Liquid%20%7B%0A%20%20%0A%20%20%20%20private%20double%20boilingPoint%3B%0A%20%20%20%20private%20double%20freezingPoint%3B%0A%20%20%20%20private%20double%20currentTemp%3B%0A%0A%20%20%20%20public%20Liquid%28%29%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20currentTemp%20%3D%2050%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20public%20void%20lowerTemp%28%29%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20currentTemp%20-%3D%2010%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20public%20double%20getTemp%28%29%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20return%20currentTemp%3B%0A%20%20%20%20%7D%0A%20%20%20%20%0A%20%20%20%20public%20static%20void%20main%28String%5B%5D%20args%29%20%7B%0A%20%20%20%20%20%20%20%20%20%20Liquid%20water%20%3D%20new%20Liquid%28%29%3B%0A%20%20%20%20%20%20%20%20%20%20water.lowerTemp%28%29%3B%0A%20%20%20%20%20%20%20%20%20%20System.out.println%28water.getTemp%28%29%29%3B%0A%20%20%20%20%7D%0A%7D&cumulative=false&curInstr=18&heapPrimitives=nevernest&mode=display&origin=opt- frontend.js&py=java&rawInputLstJSON=%5B%5D&textReferences=false
to see this code in action.)
  • The Liquid() constructor sets the currentTemp instance variable to 50 and the lowerTemp() method subtracts 10 from it.
  • The Liquid() constructor sets the currentTemp instance variable to 50 and the lowerTemp() method subtracts 10 from it.
  • water.getTemp()
  • The System.out.println will print the value returned from water.getTemp().
  • The code will not compile.
  • This code should compile.
  • 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.

Activity 1.14.17.

Consider the following methods, which appear in the same class.
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?
  • printSlices(slicesPerPerson);
  • Correct! If you had 4 people, slicesPerPerson would be 8/4=2 and printSlices would print out β€œEach person gets 2 slices each”.
  • printSlices(numOfPeople);
  • If you had 4 people, this would print out that they get 4 slices each of an 8 slice pizza.
  • printSlices(8);
  • This would always print out 8 slices each.
  • splitPizza(8);
  • This would not call the printSlices method.
  • splitPizza(slicesPerPerson);
  • This would not call the printSlices method.
You have attempted of activities on this page.