4.1 Class and Object with No Methods

To start, we will define a class, Account, corresponding to a bank account. This class will have member variables defined for account number, account name, and balance. At this stage, we have defined no methods for this class.


Account

class Account
{
int accountNo;
String accountName;
double balance;
}



The class identifier, Account, in line 1 can be any valid Java identifier. By convention, class identifiers are nouns, in mixed case with the first letter of each internal word capitalized. Member variables are declared using the syntax datatype variableName as described in Section 2.3. The code must be stored in a file Account.java.
Compilation by means of the command

> javac Account.java

will create a compiled bytecode file Account.class.

We create, or instantiate, an object using the following syntax:

classIdentifier objectName = new classIdentifier();

So to create an object fredsAccount that is an instantiation of the Account class, we would use the following statement:

Account fredsAccount = new Account();

in any program, either an application or an applet, that uses the object.

To set the member variables to a particular value, we would use the syntax

objectIdentifier.variableIdentifier = value;

So to set the account number for fredsAccount object to a value of 123, say, we would use the statement

fredsAccount.accountNo = 123;

Bringing all this together is an application, CreateAccount that creates the fredsAccount object, sets all the corresponding class member variables, and prints their values.

CreateAccount

class CreateAccount
{

public static void main(String[] args)
{
Account fredsAccount = new Account();
fredsAccount.accountNo = 123;
fredsAccount.accountName = ''Fred";
fredsAccount.balance = 50;
System.out.println("A/cno:"+ fredsAccount.accountNo +" A/c name: " + fredsAccount.accountName + " Balance:"
+ fredsAccount.balance);
}
}



We will need to compile CreateAccount by means of the command

> javac CreateAccount.java

Then we can run the program

> java CreateAccount

A/c no: 123 A/c name: Fred Balance: 50.0

No comments:

Post a Comment