为什么在子类类构造函数中添加super()不会产生错误?
问题描述:
<pre lang="java">interface Superclass {
void doSmth();
}
class Subclass implements Superclass {
Subclass() {
super();//line 1
}
@Override
public void doSmth() {
System.out.println("Do something");
}
}
I learned from a book mentioning, "Interfaces do not have constructors". But if that's the case then why there isn't a run-time error, while adding super() in the subclass constructor?
我的尝试:
What I have tried:
<pre><pre lang="java"><pre>interface Superclass {
void doSmth();
//Superclass()
//{}
}
class Subclass implements Superclass {
Subclass() {
super();
System.out.println("oca.Subclass.<init>()");
}
@Override
public void doSmth() {
System.out.println("Do something");
}
}
public class Q1
{
public static void main(String[] args) {
Superclass sc=new Subclass();//line 2
Subclass sb=new Subclass();//line 3
}
}
输出
output
oca.Subclass.<init>()
oca.Subclass.<init>()
Also, I learned that whenever there is an instantiation of a subclass, then implicitly compiler will add super() in the subclass's default constructor which in turn invokes the parent class constructor. So in this case too why didn't it produce a runtime error even?
Also, there's a compile-time error when I declare a constructor for the interface.
Could anyone help me understand this ?