子类继承和调用父类构造方法的执行顺序
1.如果子类没有定义构造方法,则调用父类的无参数的构造方法,.
2.如果子类定义了构造方法,且其第一行没有super,则不论子类构造方法是有参数还是无参数,在创建子类的对象的时候,首先执行父类无参数的构造方法,然后执行自己的构造方法。
若子类构造方法中第一行是有参数或无参数的super,则直接转到对应的有参或无参父类构造方法中,而不再是首先执行无参构造方法;
3.如果子类调用父类带参数的构造方法,可以通过super(参数)调用所需要的父类的构造方法,且该语句做为子类构造方法中的第一条语句。
4.如果某个构造方法调用类中的其他的构造方法,则可以用this(参数),切该语句放在构造方法的第一条. 说白了:原则就是,先调用父亲的.(没有就默认调,有了就按有的调,反正只要有一个就可以了.) package test; class Father{
String s = \ public Father(){ System.out.println(s); }
public Father(String str){ s= str;
System.out.println(s); } }
class Son extends Father{
String s= \ public Son(){
//实际上在这里加上super(),和没加是一个样的 System.out.println(s); }
public Son(String str){
this();//这里调用this()表示调用本类的Son(),因为Son()中有了一个super()了,所以这里不能再加了。 s = str;
System.out.println(s); }
public Son(String str1, String str2){
super(str1+\因为这里已经调用了一个父类的带参数的super(\了,所以不会再自动调用了无参数的了。
s = str1;
System.out.println(s); } }
public class MyClass9 {
public static void main(String[] args){ 1 Father obfather1 = new Father();
2 Father obfather2 = new Father(\ 3 Son obson1 = new Son(); 4 Son obson2 = new Son(\
5 Son obson3 = new Son(\ } }
=============== 结果:
1 Run constructor method of Father
2 Hello Father
3 Run constructor method of Father Run constructor method of son 4 Run constructor method of Father Run constructor method of son hello son
5 hello son hello father hello son
若son的第一个有参构造方法变为:
public Son(String str)
{
Super(str);//这里调用this()表示调用本类的Son(),因为Son()中有了一个super()了,所以这里不能再加了。
s = str;
System.out.println(s); }
则结果为:
Run constructor method of Father Hello Father
Run constructor method of Father Run constructor method of son hello son hello son
hello son hello father hello son