Could print()
use the reference to the
original String object to change the contents of that object?
No — because String
objects are immutable.
Not even the main()
method can change the original object.
It is good that String
objects are immutable (they can't be changed)
because the main()
method can be sure that the message
is completely under its control.
Although the print()
method gets a copy of the reference,
it can't change the original object.
Not all objects are immutable.
For example, in the following,
MyPoint
objects
have public instance variables x
, and y
.
These can be changed by any method
that has a referece to the object.
class MyPoint { public int x=3, y=5; public void print() { System.out.println("x = " + x + "; y = " + y ); } } class PointTester { public static void main ( String[] args ) { MyPoint pt = new MyPoint(); pt.print(); pt.x = 45; pt.y = 83; pt.print(); } }
Important: Public instance variables of objects can be changed by any method that has a reference to the object.
(If an instance variable is neither public nor private it can be changed by a method that is in the same package. For now, all of our code is in the same package, so the effect is the same as if it were public.)
The main()
method uses the default constructor of class MyPoint
.
This is the constructor you get automatically if you do not define one yourself.