java - 下面是代码片段和错误消息,为什么编译器要求这个默认构造函数?
问题描述
class X{
X(){
System.out.println("Inside X()");
}
X(int x){
System.out.println("Inside X(int)");
}
}
class Y extends X{
Y(String s){
System.out.println("Inside Y(String)");
}
Y(int y){
super(1000);
System.out.println("Inside Y(int)");
}
}
class Z extends Y{
Z(){
System.out.println("Inside Z()");
}
Z(int z){
super(100);
System.out.println("Inside Z(int)");
}
}
public class Program{
public static void main(String args[]){
Z z=new Z(10);
}
}
上面的代码在编译时给出以下错误:-
Program.java:23:错误:没有为 Y 找到合适的构造函数(无参数)
Z(){
^
constructor Y.Y(String) is not applicable
(actual and formal argument lists differ in length)
constructor Y.Y(int) is not applicable
(actual and formal argument lists differ in length)
1 个错误
当我们调用参数化构造函数时,默认构造函数有什么用,java编译器给出错误我无法理解为什么需要这个默认构造函数?
解决方案
如果它没有没有参数的构造函数(默认一个),则需要指定用于创建超类的构造函数*
构造函数中的第一个语句是调用,super()
除非您使用任何参数显式调用 this 或 super。该super()
调用由 java 在编译时注入。因此它在 Y 类中寻找非参数构造函数。
请参考文档:
注意:如果构造函数没有显式调用超类构造函数,Java 编译器会自动插入对超类的无参数构造函数的调用。如果超类没有无参数构造函数,则会出现编译时错误。Object 确实有这样的构造函数,所以如果 Object 是唯一的超类,则没有问题。
在实践中,编译器会预处理您的代码并生成如下内容:
class X{
X(){
super(); // Injected by compiler
System.out.println("Inside X()");
}
X(int x){
super(); // Injected by compiler
System.out.println("Inside X(int)");
}
}
class Y extends X{
Y(String s){
super(); // Injected by compiler
System.out.println("Inside Y(String)");
}
Y(int y){
super(1000);
System.out.println("Inside Y(int)");
}
}
class Z extends Y{
Z(){
super(); // Injected by compiler
System.out.println("Inside Z()");
}
Z(int z){
super(100);
System.out.println("Inside Z(int)");
}
}
public class Program{
public static void main(String args[]){
Z z=new Z(10);
}
}
然后它将继续编译它,但是如您所见,Z 非参数构造函数尝试引用 Y 非参数构造函数,它不存在。
*正如 Carlos Heuberger 所澄清的那样。
推荐阅读
- git - 如何丢弃我没有推送权限的分支上的提交?
- flutter - Flutter/Dart - 编辑后在构建的页面视图上自动更新标题?
- swift - 选择导航链接时如何更改文本颜色?SwiftUI Mac 催化剂
- java - 替换 XWPFParagraph 中的文本而不更改 docx 文件的格式
- flutter - 基于扩展的主题是一个很好的实践吗?
- list - 获取列表中某个元素的索引号
- python - 关于在 Python 中正确实现拉普拉斯求解器的格林函数的建议?
- flutter - Flutter BLOC 和 Provider 如何一起注册
- python - 当其他属性更改而没有@property 时更新类属性
- c# - C# SMTP 的工作原理