为什么在子类类构造函数中添加super()不会产生错误? [英] Why adding super() in subclass class constructor doesn't produce an error?
本文介绍了为什么在子类类构造函数中添加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 ?
推荐答案
参见Lesson:接口和继承(Java™教程>学习Java语言) [ ^ ]。
这篇关于为什么在子类类构造函数中添加super()不会产生错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文