4.6 Instance and Static Variables in Java

By default, class member variables are instance variables. In the Account class shown next, accountNo, accountName, and balance are all instance variables.

Account

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


Whenever an object, or instance, of the class is created, copies of the instance variables are created. In CreateAccount, two instances of the Account class are created: fredsAccount and billsAccount. The instancevariablescorresponding to fredsAccount and billsAccount are assigned values.

CreateAccount

class CreateAccount
{

public static void main(String[] args)
{
Account fredsAccount = new Account();
fredsAccount.accountNo = 123;
fredsAccount.accountName = ''Fred";
fredsAccount.balance = 50;
Account billsAccount = new Account();
billsAccount.accountNo = 456;
billsAccount.accountName = "Bill";
billsAccount.balance = 75;
System.out.println("Freds A/c no: "
+ fredsAccount.accountNo + " Freds A/c name:" + fredsAccount.accountName + " Freds balance: " + fredsAccount.balance);
System.out.println(''Bills A/c no: " + billsAccount.accountNo +”Bills A/C name: " + billsAccount.accountName +”Bills Balance:” + billsAccount.balance);
}
}


When we assign a value of 456 to billsAccount.accountNo, the value of fredsAccount.accountNo is unaffected because Java has created two copies of accountNo corresponding to billsAccount and fredsAccount. The result of executing the program is shown as follows:

> java CreateAccount
Freds A/c no: 123 Freds A/c name: Fred Freds Balance: 50.0
Bills A/c no: 456 Bills A/c name: Bill Bills Balance: 75.0


A member variable can be defined as a static (or class) variable by use of the static keyword. In this case, a single copy of the member variable is created regardless of the number of instances (even if no instances are created). Each instance has access to the same copy of the static variables. We would make a variable static if it is the same for all objects. For example, we can add the static variable bankName to the Account class definition.

Account

class Account
{
static String bankName;
int accountNo;
String accountName;
int balance;
}



Suppose we add the following statements to the CreateAccount program:

fredsAccount.bankName = "Ealing Bank";
billsAccount.bankName = "Kingston Bank";


After the second statement is executed, the value of fredsAccount.bankName is also "Kingston Bank" since the billsAccount and fredsAccount objects share the same copy of the bankName variable. Normally, we would not prefix a static variable with an object since it does not make sense to associate a static variable with an object. We prefix static variables with the class name, as follows:

Account.bankName = ''Ealing Bank";

No comments:

Post a Comment