父类构造方法对子类构造方法的影响
1、super()用于调用父类构造方法
public class Father {
public Father() {
super();//调用Object类中的构造方法
System.out.println("父类无参构造方法");
}
}
public class Son extends Father{
public Son() {
super();
System.out.println("子类无参构造方法");
}
public static void main(String[] args) {
new Son();
}
}
super()调用父类构造方法,该行代码必须放在有效代码行第一行。
2、如果一个构造方法没有调用本类中的其它构造方法,则该构造方法默认调用super(),反之没有super();
public class Father {
String name;
int age;
String id;
public Father() {
super();//调用Object类中的构造方法
System.out.println("父类无参构造方法");
}
}
public class Son extends Father{
public Son() {
this(20);
System.out.println("子类无参构造方法");
}
public Son(int age) {
this.age = age;
}
public static void main(String[] args) {
new Son();
}
}
子类Son中的无参构造方法调用另一个构造方法,则子类无参构造方法中不能调用super(),但子类被调用的构造方法中仍然有super()调用了父类的无参构造方法。
3、如果父类拥有无参构造方法(无论是显式还是隐式),且子类中的没有明确指出调用父类的哪个构造方法,则子类中没有调用本类其它构造方法的构造方法使用super()隐式调用父类的无参构造方法。
public class Father {
String name;
int age;
String id;
public Father() {
super();//调用Object类中的构造方法
System.out.println("父类中的无参构造方法......");
}
public Father(String name) {
this.name = name;
}
}
public class Son extends Father{
public Son(String name,int age) {
System.out.println("子类构造方法");
this.age = age;
this.name = name;
}//该构造方法隐式调用了父类的无参构造方法
public static void main(String[] args) {
Son son = new Son("李雷",20);
System.out.println("我叫"+son.name+"今年"+son.age+"岁");
}
}
子类Son中的构造方法 public Son(String name,int age)没有明确指出调用父类的哪个构造方法,则默认调用父类的无参构造方法。
public class Father {
String name;
int age;
String id;
public Father() {
super();//调用Object类中的构造方法
System.out.println("父类中的无参构造方法......");
}
}
public class Son extends Father{
public Son(String id) {
this();
this.id = id;
System.out.println("子类构造方法");
}
public Son() {
System.out.println("子类无参构造方法");;
}
public static void main(String[] args) {
new Son("20172430521");
}
}
子类Son中的无参构造方法没有调用本类中的其它的构造方法也没有明确指出调用父类的哪一个构造方法,因此该构造方法默认通过super()隐式调用父类Father中的无参构造方法。
子类Son中的有参构造方法调用本类中的无参构造方法,因此该构造函数不能通过super()调用父类中的构造方法,这一点可以通过程序运算结果中看出。
4、如果父类中没有构造方法(无论是显式还是隐式),则子类中的构造方法必须直接或间接的指出调用父类的哪一个构造方法,并且放在有效代码行的第一行。
public class Father {
String name;
int age;
String id;
public Father(String name) {
this.name = name;
System.out.println("父类构造方法");
}
public Father(int age) {
this.age = age;
System.out.println("父类构造方法");
}
}
public class Son extends Father{
public Son(String name,String id) {
super(name);
this.id = id;
System.out.println("子类构造方法");
}
public Son(String name,String id,int age) {
this(name,id);
this.age = age;
System.out.println("子类构造方法");
}
public static void main(String[] args) {
new Son("李雷","110",20);
}
}
子类中的第一个构造方法直接调用父类的第一个构造方法,子类中的第二个构造方法间接调用父类的第一个构造方法。
总之,子类必须调用父类的构造方法。