【发布时间】: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