Skip to main content

Section 6.8 Calling Methods Without Parameters

Methods are a set of instructions that define behaviors for all objects of a class. For example, in the Player class, methods like heal() and attack() give Player objects the ability to heal and attack.
To use an object’s method, you must use the object name and the dot (.) operator followed by the method name, for example, p1.heal(); calls p1’s heal method. These are called object methods or non-static methods. An object method must be called on an object of the class that the method is defined in. Object methods work with the attributes of the object, such as the direction the turtle is heading or its position.
Every method call is followed by parentheses. The parentheses () after method names are there in case you need to give the method parameters (data) to do its job, which we will see in the next lesson. You must always include the parentheses after the method name.

Note 6.8.1.

object.method(); is used to call an object’s method.

Subsection 6.8.1 Procedural Abstraction

Procedural abstraction allows a programmer to use a method and not worry about the details of how it exactly works. For example, we know that if we hit the brakes, the car will stop, and we can still use the brakes even if we don’t really know how they work.
In addition to writing your own methods, you should be able to use methods already written for you and figure out what they do. When we use methods for a class in a library, we can look up the method signature (or method header), which is the method name followed by a parameter list, in its documentation. For example, here is a Student class with a method signature public void print() which has an empty parameter list with no parameters. Methods are defined after the instance variables (attributes) and constructors in a class.
Figure 6.8.2. Figure 1: A Student class showing instance variables, constructors, and methods.
The Java visualization below shows how a song can be divided up into methods. Click on the next button below the code to step through the code. Execution in Java always begins in the main method in the current class. Then, the flow of control skips from method to method as they are called. The Song’s print method calls the chorus() and animal() methods to help it print out the whole song.
When you call the chorus() method, it skips to the chorus code, executes and prints out the chorus, and then returns back to the method that called it.
Methods inside the same class can call each other using just methodName(), but to call non-static 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 6.8.3. Figure 2: Calling non-static methods from main() or from other methods inside the same class.
Try this visualization to see this code in action.

Note 6.8.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. Remember that 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.

Subsection 6.8.2 Summary

  • Methods are a set of instructions that define the behaviors for all objects of the class.
  • Use dot notation to execute an object’s method. This is the object’s name followed by the dot (.) operator followed by the method name and parentheses: object.method();
  • 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.
  • Procedural abstraction allows a programmer to use a method by knowing in general what it does without knowing what lines of code execute. This is how we can drive a car without knowing how the brakes work.
  • A method or constructor 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.
  • A NullPointerException will happen if you try to call an object method on an object variable whose value is null. This usually means that you forgot to create the object using the new operator followed by the class name and parentheses.
  • An object method or non-static method is one that must be called on an object of a class. It usually works with the object’s attributes.
  • A static method or class method method is one that doesn’t need to be called on an object of a class.

Subsection 6.8.3 Practice

Checkpoint 6.8.5.

Checkpoint 6.8.6.

What does the following code print out?
  public class Song
  {
    public void print()
    {
        System.out.print("I like to ");
        eat();
        eat();
        eat();
        fruit();
    }

    public void fruit()
    {
        System.out.println("apples and bananas!");
    }

    public void eat()
    {
       System.out.print("eat ");
    }

    public static void main(String[] args)
    {
       Song s = new Song();
       s.print();
    }
}
  • I like to eat eat eat.
  • Try tracing through the print method and see what happens when it calls the other methods.
  • I like to eat eat eat fruit.
  • There is a fruit() method but it does not print out the word fruit.
  • I like to apples and bananas eat.
  • The order things are printed out depends on the order in which they are called from the print method.
  • I like to eat eat eat apples and bananas!
  • Yes, the print method calls the eat method 3 times and then the fruit method to print this.
  • Nothing, it does not compile.
  • Try the code in an active code window to see that it does work.

Checkpoint 6.8.7.

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.

Checkpoint 6.8.8.

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 “.

Checkpoint 6.8.9.

The following Java code defines a Player class with movement methods, allowing the player to move up and left based on its current direction. However, the code blocks are out of order. Your task is to rearrange the code blocks so that the player:
  1. Moves up first.
  2. Turns left.
  3. Moves left afterward.
The player starts at position (0,0) and is initially facing up. Once the blocks are correctly arranged, the final position should be (-10, 10), and the player should be facing left. Click on the “Check Me” button to check your solution.
public class Player {
    private int x, y;
    private String direction; // Possible values: "up", "down", "left", "right"

    public Player() {
        this.x = 0;
        this.y = 0;
        this.direction = "up"; // Default direction
    }

    public Player(int x, int y) {
        this.x = x;
        this.y = y;
        this.direction = "up"; // Default direction
    }

    public void forward(int distance) {
        y += distance;
    
    }

    public void turnLeft() {
        direction = "left";
    }

    public void turnRight() {
        direction = "right";
    }

    public void faceUp() {
        direction = "up";
    }

    public void faceDown() {
        direction = "down";
    }

    public int[] getPosition() {
        return new int[]{x, y};
    }

    public void printStatus() {
        System.out.println("Player Position: (" + x + ", " + y + ")");
        System.out.println("Facing: " + direction);
    }
}
You have attempted of activities on this page.