First value of message: Only One Object Value of parameter: Only One Object Second value of message: Only One Object
The program works as you expect.
The diagram shows what is
happening.
The main()
method creates a String
object that
contains the characters "Only One Object."
A reference to this object is held in the reference variable messsage
.
A reference to an object is a way to find the object in main memory. If a method has a reference to an object, then in can use that object.
Now an ObjectPrinter
object is created and
a reference to it is placed in op
.
In the statement op.print(message)
,
the reference to the object is passed as the value
of the parameter.
This is just like call by value with a primitive data type,
but now the value is a reference.
The invoked method print()
uses its formal parameter
st
to find the object,
and print out the object's data.
If print()
changes the value held in st
,
will this change the actual object?