Overview


Sending messages to methods that return values is done the same way as simple messages.

The only difference is that the return value may be used by the caller.

Here is our previous code.
Rectangle rec;
rec = new Rectangle();

rec.setSmall();
Recall from our previous work here... that the method "getWidth" returns an "int" value.

  • Send the message "getWidth" to the "rec" object
  • Assign the returned value to the var "w"

Variable names like "w" here are coder's choice -- we could use "w", "width", "ww", "fred", etc
Rectangle rec;
rec = new Rectangle();

rec.setSmall();

int w;
2
w =
1
rec.getWidth();
We can also use the return value anywhere the type is valid. In this case the value type is "int".


  • We use the value 10 in a summation which is fine (10 is an "int" data type)
  • But we can also use the return value from getWidth() (also an "int")
Rectangle rec;
rec = new Rectangle();

rec.setSmall();

int sum;


sum = 
1
10 + 20; sum =
2
rec.getWidth() + rec.getHeight();