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 message
.
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 it 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 works 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.
Only one object exists during a run of this program.
However, when the method is called there are two
variables that point to the object: message
and the parameter st
.
The parameter works as an alias for the object while the method is active.
If print()
changes the value held in st
,
will this change the actual object?