Java Reference
In-Depth Information
memory from the system to store the Account object, then implicitly calls the class's con-
structor to initialize the object. The call is indicated by the parentheses after the class
name, which contain the argument "Jane Green" that's used to initialize the new object's
name. The class instance creation expression in line 10 returns a reference to the new ob-
ject, which is assigned to the variable account1 . Line 11 repeats this process, passing the
argument "John Blue" to initialize the name for account2 . Lines 14-15 use each object's
getName method to obtain the names and show that they were indeed initialized when the
objects were created . The output shows different names, confirming that each Account
maintains its own copy of instance variable name .
1
// Fig. 3.6: AccountTest.java
2
// Using the Account constructor to initialize the name instance
3
// variable at the time each Account object is created.
4
5
public class AccountTest
6
{
7
public static void main(String[] args)
8
{
9
// create two Account objects
Account account1 = new Account( "Jane Green" );
Account account2 = new Account( "John Blue" );
10
11
12
13
// display initial value of name for each Account
14
System.out.printf( "account1 name is: %s%n" , account1.getName());
15
System.out.printf( "account2 name is: %s%n" , account2.getName());
16
}
17
} // end class AccountTest
account1 name is: Jane Green
account2 name is: John Blue
Fig. 3.6 | Using the Account constructor to initialize the name instance variable at the time each
Account object is created.
Constructors Cannot Return Values
An important difference between constructors and methods is that constructors cannot re-
turn values , so they cannot specify a return type (not even void ). Normally, constructors
are declared public —later in the topic we'll explain when to use private constructors.
Default Constructor
Recall that line 13 of Fig. 3.2
Account myAccount = new Account();
used new to create an Account object. The empty parentheses after “ new Account ” indicate a
call to the class's default constructor —in any class that does not explicitly declare a construc-
tor, the compiler provides a default constructor (which always has no parameters). When a
class has only the default constructor, the class's instance variables are initialized to their de-
fault values . In Section 8.5, you'll learn that classes can have multiple constructors.
 
Search WWH ::




Custom Search