以下是继承的示例
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();
}
}
Run Code Online (Sandbox Code Playgroud)
当我没有非参数化构造函数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)
Run Code Online (Sandbox Code Playgroud)
能否请您解释一下在基类中没有参数的构造函数的用途是什么.
class child extends parent
{
child(int a,int b)
{
int c=a-b;
System.out.println("Difference="+c);
}
}
Run Code Online (Sandbox Code Playgroud)
子类构造函数必须做的第一件事是调用父类构造函数.如果您没有明确地执行此操作(例如super(a,b)),则隐含(super())默认构造函数的调用.
为此,您必须具有此默认构造函数(不带任何参数).
如果您没有声明任何构造函数,那么您将获得默认构造函数.如果声明至少一个构造函数,则不会自动获取默认构造函数,但可以再次添加它.
您收到的错误消息是抱怨隐含的调用super()不起作用,因为父类中没有这样的构造函数.
有两种方法可以解决它:
super(a,b))另外,请不要使用全小写的类名.