4.8 Using this Keyword Java

class Account
{
int accountNo; String accountName; double balance;
public Account(int no, String name, double bal)
{
accountNo = no; accountName = name; balance = bal;
}


What if we used the same identifiers for member and local variable in the constructor, as follows:

public Account(int accountNo, String accountName, double balance)
{
accountNo = accountNo; accountName = accountName; balance = balance;
}


Although this will compile successfully, Java cannot distinguish between the left-side member variables and the right-side local variables. Variables on both sides of the assignment operators are treated as local; the member variables are not set by the constructor. As a result, the value of fredsAccount.accountNo, after invoking the constructor in the following code fragment, is 0, the default value for integers in Java, rather than 123.

Account fredsAccount = new Account(123, ''Fred", 60);

To specify an object's member variables, Java provides the this keyword, which is prefixed to the member variable or method. The Account class constructor can be written as

public Account(int accountNo, String accountName, double balance)
{
this.accountNo = accountNo;
this.accountName = accountName;
this.balance = balance;
}


The value of fredsAccount.accountNo after invoking the constructor

Account fredsAccount = new Account(123, ''Fred", 60);

is 123 as expected.

this is actually a reference to the object being constructed. All object variables are references, so the following code fragment:

Account fredsAccount = new Account(...); Account billsAccount = fredsAccount; billsAccount.balance = 500;

sets the balance for both Bill and Fred.

No comments:

Post a Comment