构造函数(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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值