English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have got one question.In Java Programming where we have to use private constructor.Also if there any sample Banking application? just guide me?

2007-03-09 21:11:03 · 2 answers · asked by melksi 1 in Computers & Internet Programming & Design

2 answers

A private constructor prevents other code from creating objects of your type by using the "new" operator. Instead, you typically provide them with some other way of getting an instance, such as a factory class or via a constant static reference.

Example:
//Don't want other code to be able to create non-existant accounts

public final class Account{

private String fAcctID;
private Customer fAcctHolder;

private Account(String ID, Customer holder){
fAcctID = ID;
fAcctHolder = holder;
}

public getAccountHolder(){
return fAcctHolder.clone();//defensive copy
}

public getAccountID(){
return fAcctID;
}

public static getAccount(String ID){
//code that uses JDBC to retrieve "real" account data
//and then uses it to create an Account object
Account acct = new Account(id, holder);
return acct;
}

}

Now, there is no way for someone to change an account by manipulating an Account object or creating a new one with erroneous data (prevents mischief, programming errors, etc.). Also note that I combined the private constructor with a static "factory" method and made the class "final" (to prevent substitution of a mutable sub-class instance).

2007-03-12 10:44:56 · answer #1 · answered by vincentgl 5 · 0 0

What's the question about private constructors?

2007-03-09 22:22:22 · answer #2 · answered by Tasm 6 · 0 0

fedest.com, questions and answers