4.3 Java Constructors

Java provides a special kind of method, called a constructor, that executes each time an instance of an object is created. The constructor can be used to initialize the state of an object. The call to new, which creates an object, invokes the new object's constructor. The constructor has the same identifier as its class and does not define a return type. The following code fragment shows the Account constructor that sets the account number, name, and balance to supplied values:

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


This code would be added to the Account class definition in the same way as the deposit and withdrawal methods. The Account class now includes its constructor.


Account

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

public Account(int no, String name, double bal)
{

accountNo = no;
accountName = name;
balance = bal;
}
public void deposit(double amount)
{
balance = balance + amount;
}

public double withdraw(double amount)
{
if (balance - amount < 0)
{
System.out.println(''Insufficient Funds");
}
Else
{
balance = balance - amount;
}
return balance;
}
}


The statements (lines 4–7) in the CreateAccount application in Section 4.1, which create the fredsAccount object and initialize the corresponding class member variables, can now be replaced by the single statement

Account fredsAccount = new Account(123, "Fred", 50);

If a class does not have a constructor, then Java creates a default constructor. This has no parameters, and all instance variables are set to their default values. So for the Account class, the default constructor will be equivalent to

public Account()
{
accountNo =0;
accountName = null; balance = 0.0;
}


Consequently, the statement

Account fredsAccount = new Account();

is legal if the Account class does not have a constructor. However, if a class has one or more constructors and does not explicitly include a constructor without parameters, the preceding statement is illegal. We cannot rely on a default constructor as a fallback in this case.

No comments:

Post a Comment