【发布时间】:2011-05-31 01:33:08
【问题描述】:
下面是继承的例子
class Parent {
Parent(int a, int b) {
int c = a + b;
System.out.println("Sum=" + c);
}
void display() {
System.out.println("Return Statement");
}
}
class Child extends Parent {
Child(int a, int b) {
int c = a - b;
System.out.println("Difference=" + c);
}
}
public class InheritanceExample {
public static void main(String args[]) {
Child c = new Child(2, 1);
c.display();
}
}
当我没有非参数化构造函数 parent() 时出现以下错误
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor
at Child.<init>(InheritanceExample.java:14)
at InheritanceExample.main(InheritanceExample.java:22)
你能解释一下无参数构造函数在基类中的用途吗?
【问题讨论】:
-
在这种情况下,它只是一个创建父类实例的默认构造函数。通常您会将对象变量设置为某个默认值或 null。
-
请包含错误的文本,而不是屏幕截图。
-
真的是源代码吗?它通过复制/粘贴为我编译并运行良好。
-
@TofuBeer:如果您在基类中包含不带参数的构造函数,它将编译。如果没有,它不会。
-
是 Java 约定在类中使用大写字母并在同一行中使用大括号。
标签: java