本文共 1092 字,大约阅读时间需要 3 分钟。
子类不能继承父类的构造器(构造方法或者构造函数),但是父类的构造器带有参数的,则必须在子类的构造器中显式地通过super关键字调用父类的构造器并配以适当的参数列表。
class A { private int n; A(int n) { System.out.println("A(int n)"); this.n = n; } } class B extends A{ private int n; B(){ super(300); System.out.println("B"); } } public class TestSuperSub{ public static void main (String args[]){ B b = new B(); } }
输出
A(int n)B
如果父类有无参构造器,则在子类的构造器中不是必须得用super调用父类构造器,如果没有使用super关键字,系统会自动调用父类的无参构造器。
class A { private int n; A(){ System.out.println("A()"); } A(int n) { System.out.println("A(int n)"); this.n = n; } } class B extends A{ private int n; B(){ super(300); System.out.println("B"); } public B(int n){ System.out.println("B(int n):"+n); this.n = n; } } public class TestSuperSub{ public static void main (String args[]){ B b1 = new B(); B b2 = new B(200); } }
输出
A(int n)BA()B(int n):200
转载地址:http://irlai.baihongyu.com/