【问题标题】:Compilation error when instantiating object实例化对象时编译错误
【发布时间】:2019-11-01 09:14:35
【问题描述】:

我只想制作一个对象。但我不知道为什么会出现这个错误。我认为一切都是正确的,但弹出构造函数错误。它说需要 String,String,int 没有参数。这是为什么呢?

error: constructor Account in class Account cannot iven types required: String,String,int found: no arguments reason: actual and formal argument

我的代码

class Account{
    private String accName;
    private String accID;
    private int balance;
    private Account(){
        accName = "No name found";
        accID = "No id found";
    }
    private Account(String name, String id, int bal){
        accName = name;
        accID = id;
        balance = bal;
    }
    private void Withdrow(int amount){
        if(balance > amount)
        {
        balance = balance - amount;
        System.out.println("Balance :"+balance);
        }
        else
            System.out.println("Not Enough money");
    }
    private void deposit(int amount){
        if(amount>0)
        {
        balance = balance + amount;
        System.out.println("Balance :"+balance);
        }
        else
            System.out.println("Error Deposit");
    }
    private void showInfo(){
        System.out.println("Name :"+ accName);
        System.out.println("ID :"+ accID);
        System.out.println("Balance :"+ balance);
    }
}

class Main{

    public static void main(String args[]){

        Account ac = new Account();

    }
}

【问题讨论】:

  • 无参数构造器是私有的。在使用参数化对象创建对象时,要么将其公开,要么使用参数。

标签: java constructor access-modifiers


【解决方案1】:

公开你的构造函数并初始化balance属性

public Account(){
    accName = "No name found";
    accID = "No id found";
    balance = 0;
}

【讨论】:

  • @lealceldeiro 依赖这样的默认值通常被认为是糟糕的编程风格。
猜你喜欢
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 2014-08-04
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
相关资源
最近更新 更多