1.3.10 Calling a Method on Another Object

Video: Calling Methods between Objects (13:38)
Objects Can Ask Other Objects to Perform Behavior

You have already created objects and called methods such as:

team1.DisplayName();

That statement asks the object referenced by team1 to run its DisplayName method.

An object can also call a method on another object that it can reach.

This is one of the basic ways objects cooperate inside a program.

Start with Two Related Objects

Suppose the program has these two classes:

class Player
{
    public Team team;

    public void ShowTeamName()
    {
    }
}
class Team
{
    public string name;

    public void DisplayName()
    {
        System.Console.WriteLine(this.name);
    }
}

The Player has a reference to a Team object.

At runtime:

Player player1 = new Player();
Team team1 = new Team();

team1.name = "Wildcats";
player1.team = team1;

The objects are now related.

The Current Object Can Call the Related Object

Inside Player, the ShowTeamName method can call the Team method:

public void ShowTeamName()
{
    this.team.DisplayName();
}

Read the statement from left to right:

Activity diagram showing this, then team, then DisplayName().
This.
  • New
  • Changed
  • Removed

Plain language:

The Receiver Determines Which Object's Method Runs

In:

this.team.DisplayName();

the receiver is:

Object diagram showing create objects, then assign object reference, then call method on related object.
CreateObjects.
  • New
  • Changed
  • Removed
The Called Method Uses Its Own Current Object

When:

this.team.DisplayName();

calls DisplayName, the current object inside DisplayName is the Team object.

So inside:

public void DisplayName()
{
    System.Console.WriteLine(this.name);
}

this.name refers to the Team's name.

The Player started the call.

The Team owns the method that is now executing.

One Call Can Cross an Object Boundary

That boundary is important.

Before the call:

current code is running on Player

After entering DisplayName():

current code is running on Team

The method call transfers execution into another object's behavior.

Use Method Calls Instead of Reaching into Unrelated State When the Design Provides Behavior

If the Team already provides:

DisplayName()

then the Player can call that behavior.

Do not duplicate the same output logic inside Player merely to avoid an object-to-object call.

The method gives Team responsibility for its own behavior.

Keep the Current Scope Simple

At this stage, method calls use:

  • no parameters;
  • no returned values.

The basic pattern is:

objectReference.MethodName();

The important question is:

That question becomes central when you trace nested method calls next.