首页 > 解决方案 > 默认情况下不应该设置构造函数吗?

问题描述

所以我正在写练习这个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() 构造函数?

标签: javaoopinheritanceconstructor

解决方案


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

您可以在这里找到类似的问题:Java 默认构造函数


推荐阅读