go to previous page   go to home page   go to next page        

Answer:

No. A constructor is used once per object. Once an object has been created the constructor is finished.

Dot Notation

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 example program creates a String object, referred to by the variable str1.

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()

The length() method is a member of the object. To run a method of the object referenced by str1 do this:

len  = str1.length();  

This assignment statement, as always, does its work in two steps:

  1. The expression on the right of the = is evaluated.
  2. The resulting value is stored in the variable on the left of the = 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.

QUESTION 15:

Do you think that the following is correct?

str1.length() = 12 ;  // change the length of str1