java - 默认情况下不应该设置构造函数吗?
问题描述
所以我正在写练习这个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() 构造函数?
解决方案
仅当您没有为对象指定特定构造函数时,才会构建默认构造函数。对于您的 Account 类,您已经定义了一个带有 4 个参数的构造函数。当您扩展此 Account 类时,您必须调用 Account 类的指定构造函数。
您可以在这里找到类似的问题:Java 默认构造函数
推荐阅读
- python - 使用 Bash 脚本(Ubuntu 上的 Gnome)打开终端选项卡时消失
- javascript - 按钮效果仅在功能结束后生效
- reactjs - React + Typescript:仅来自 `cloneElement` 的道具
- javascript - 在 JavaScript 中将日期时间字符串转换为 UTC 日期
- webview2 - 具有 WebView2 运行时依赖项的 C# 安装程序
- angular - 在 appflow 中构建 app 离子电容器时出错
- amazon-web-services - AWS 云中的视频编辑和存储
- kubernetes - 在ansible上创建一个隐藏目录
- ios - 使用 SwiftUI 3 .badge 修饰符时更新 TabView 徽章会重新加载所有视图
- javascript - 如何检索选定的复选框项目并将它们显示在窗口中?