【问题标题】:Aren't constructors supposed to be set by default? [duplicate]默认情况下不应该设置构造函数吗? [复制]
【发布时间】:2021-05-14 23:43:44
【问题描述】:

所以我正在编写关于继承的 Java 程序练习...我创建了一个父类(帐户)和一个子类(储蓄)...当我尝试运行程序时它说“没有可用的默认构造函数在 com.company.Account" 中突出显示 Savings 类。

class Account{
   //properties and methods are present here
   public class Account(){ //If I don't write this then the program will not run even though I have set a parameterized Constructor 
   }

   public Account(String acno, String name, String dob, String address){ // Parameterized Constructor
        this.acno=acno;
        this.name=name;
        this.dob=dob;
        this.address=address;
        setBalance(0);
    }
}

class Savings extends Account{ //This portion gets highlighted if I dont write Account() constructor
//Random codes present here
}

当我自己在 Account 上设置默认构造函数时,它没有显示错误并且程序运行顺利。

默认构造函数不应该自动设置吗?为什么继承时需要手动编写 Account() 构造函数?

【问题讨论】:

  • 因为您已经在类中编写了另一个构造函数。仅当类没有显式构造函数时才添加隐式构造函数。

标签: java oop inheritance constructor


【解决方案1】:

只有当你没有为你的对象指定一个特定的构造函数时,才会构建一个默认构造函数。对于您的 Account 类,您已经定义了一个带有 4 个参数的构造函数。当你扩展这个 Account 类时,你必须调用 Account 类的指定构造函数。

你可以在这里找到类似的问题:Java default constructor

【讨论】:

    猜你喜欢
    • 2011-06-07
    • 1970-01-01
    • 2016-06-17
    • 2020-11-22
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多