Java Reference
In-Depth Information
returns a particular Account object's name to the caller. The method has an empty parame-
ter list, so it does not require additional information to perform its task. The method re-
turns a String . When a method that specifies a return type other than void is called and
completes its task, it must return a result to its caller. A statement that calls method get-
Name on an Account object (such as the ones in lines 16 and 26 of Fig. 3.2) expects to re-
ceive the Account 's name—a String , as specified in the method declaration's return type .
The return statement in line 18 of Fig. 3.1 passes the String value of instance vari-
able name back to the caller. For example, when the value is returned to the statement in
lines 25-26 of Fig. 3.2, the statement uses that value to output the name.
3.2.2 AccountTest Class That Creates and Uses an Object of Class
Account
Next, we'd like to use class Account in an app and call each of its methods. A class that
contains a main method begins the execution of a Java app. Class Account cannot execute
by itself because it does not contain a main method—if you type java Account in the com-
mand window, you'll get an error indicating “ Main method not found in class Account .”
To fix this problem, you must either declare a separate class that contains a main method
or place a main method in class Account .
Driver Class AccountTest
To help you prepare for the larger programs you'll encounter later in this topic and in in-
dustry, we use a separate class AccountTest (Fig. 3.2) containing method main to test class
Account . Once main begins executing, it may call other methods in this and other classes;
those may, in turn, call other methods, and so on. Class AccountTest 's main method cre-
ates one Account object and calls its getName and setName methods. Such a class is some-
times called a driver class —just as a Person object drives a Car object by telling it what to
do (go faster, go slower, turn left, turn right, etc.), class AccountTest drives an Account
object, telling it what to do by calling its methods.
1
// Fig. 3.2: AccountTest.java
2
// Creating and manipulating an Account object.
3
import java.util.Scanner;
4
5
public class AccountTest
6
{
7
public static void main(String[] args)
8
{
9
// create a Scanner object to obtain input from the command window
10
Scanner input = new Scanner(System.in);
11
12
// create an Account object and assign it to myAccount
Account myAccount = new Account();
13
14
15
// display initial value of name (null)
16
System.out.printf( "Initial name is: %s%n%n" ,
myAccount.getName()
);
17
Fig. 3.2 | Creating and manipulating an Account object. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search