class SuperClass {
private int n;
SuperClass(){
System.out.println("SuperClass()");
}
SuperClass(int n) {
System.out.println("SuperClass(int n)");
this.n = n;
}
}
class SubClass extends SuperClass{
private int n;
SubClass(){
super(300);
System.out.println("SubClass");
}
public SubClass(int n){
System.out.println("SubClass(int n):"+n);
this.n = n;
}
}
public class TestSuperSub{
public static void main (String args[]){
SubClass sc = new SubClass();
SubClass sc2 = new SubClass(200);
}
}
请问为什么说:1.子类不能继承父类的构造器(构造方法或者构造函数),但是父类的构造器带有参数的,则必须在子类的构造器中显式地通过super关键字调用父类的构造器并配以适当的参数列表。
该案例中,(1)子类SubClass已经继承了父类SuperClass,里面的构造器不是已经发生继承了?
么?(2)该处子类SubClass的SubClass()方法是重写的还是继承的哈?这里应该是无常的构造器哈,怎么也有super(300)啊?
跪求指教哈!!
Subclasses cannot inherit the constructor of the parent class. The subclass will instantiate the parent class before instantiating it.
SubClass() is the default constructor, not overriding or inheriting. super(300) is written by you, and super() is called by default in SubClass(int n).