构造函数(constructor)

构造函数的特点:

1.与类名相同

2.没有返回值

3.利用构造函数可以对全局变量进行初始化

4.没有显式的构造函数,则jvm提供一个默认的构造函数(没有参数)。

5.如果写了构造函数,则默认的构造函数将被取代

下面给出一个实例:

public class accountDemo {

/** Creates a new instance of accountDemo */
public accountDemo() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("***********************************now is bobo's account*****************************");
Account a1 = new Account();
a1.getData(100,"bobo",1000.0);
a1.withdraw(200.0);
a1.display();

System.out.println("***********************************now is ethan's account*****************************");
Account a2 = new Account(200);
a2.getData(200,"ethan",1000.0);
a2.withdraw(2000.0);
a2.display();

System.out.println("***********************************now is jack's account*****************************");
Account a3 = new Account(300,"jack");
a3.getData(300,"jack",10000.0);
a3.withdraw(2000.0);
a3.display();

System.out.println("***********************************now is jimmy's account*****************************");
Account a4 = new Account(400,"jimmy",5000.0);
// a4.getData(400,"jimmy",5000.0);
a4.withdraw(2000.0);
a4.display();

}

}
class Account
{
int accNo;
String accName;
double accBalance;

Account()
{
this.accNo=0;this.accName=null;this.accBalance=0.0;
}

Account(int i)
{
this.accNo = i;
}

Account(int i,String s)
{
this.accNo = i;
this.accName = s;
}

Account(int i,String s,double d)
{
this.accNo = i;
this.accName = s;
this.accBalance =d;
}

void getData(int i,String s,double d)
{
this.accNo = i;
this.accName = s;
this.accBalance = d;
}
void withdraw(double amt)
{
if(amt<accBalance)
{
accBalance = accBalance - amt;
}
else
{
System.out.println("the number you input is outof your deposit,please input again ");
}

}
void deposit(double amt)
{
accBalance = accBalance + amt;
}
void display()
{
System.out.println("The number of account is :"+accNo);
System.out.println("The name of account is :"+accName);
System.out.println("The balance of account is :"+accBalance);
}
}

你可能感兴趣的:(Constructor)