No. A constructor is used once per object. Once an object has been created the constructor is finished.
String str1; // str1 is a reference to an object.
int len;
str1 = new String("Random Jottings"); // create an object of type String
len = str1.length(); // invoke the object's method length()
After an object has been constructed it can (usually) be changed by
using its own methods (not its constructor).
However, some objects are designed so that their data
cannot be changed after the object has been constructed.
The class String
is one of these.
String objects are immutable.
This means that after construction,
they cannot be altered.
The variables and methods of an object are called the members of that object. The members of an object are accessed using dot notation.
The length()
method is a member of the object created by the example.
To run this method do this:
len = str1.length();
This assignment statement, as always, does its work in two steps:
=
is evaluated.=
sign.
The right side of this particular assignment statement executes the
method length()
which is member of the object referenced by str1
.
Executing this method
returns the number of characters in the object.
Do you think that the following is correct?
str1.length() = 12 ; // change the length of str1