class Person{ String name; int age; //public Person(){} public Person(String name, int age){ this.name = name; this.age = age; System.out.println("父类构造器"); } public void info(){ System.out.println(name + " " + age); } } public class ManTest extends Person{ public ManTest(String name, int age){ this.name = name; this.age = age; //super(name, age); } public static void main(String[] args){ ManTest mt = new ManTest("zed", 18); } }
上面程序会报错,无法将Person中的构造器给定类型。这是因为在Xx类里定义了一个带参数的构造方法,那么这个Xx类就没有无参数的构造方法了。子类在继承父类时,如果没有相同的带参构造方法,那么他就需要在其构造方法中明确的通过super()调用父类的带参构造方法,否则构造不出父类,从而也构造不出他自己了。你如果在父类中写个不带参数的构造方法,就可以不用实现父类的带参构造方法了。
在父类构造器中添加无参构造器即可:
class Person{ String name; int age; //无参父类构造器 public Person(){} public Person(String name, int age){ this.name = name; this.age = age; System.out.println("父类构造器"); } public void info(){ System.out.println(name + " " + age); } } public class ManTest extends Person{ public ManTest(String name, int age){ this.name = name; this.age = age; } public static void main(String[] args){ ManTest mt = new ManTest("zed", 18); } }
或者在子类调用父类带参构造器:
class Person{ String name; int age; public Person(String name, int age){ this.name = name; this.age = age; System.out.println("父类构造器"); } public void info(){ System.out.println(name + " " + age); } } public class ManTest extends Person{ public ManTest(String name, int age){ //调用父类带参构造器 super(name, age); } public static void main(String[] args){ ManTest mt = new ManTest("zed", 18); } }
子类构造方法前要先调用父类构造方法,如果父类没有无参构造,就需要通过super()调用父类有参构造。如果父类有无参构造方法,子类会直接调用父类的无参构造。