super()调用父类构造方法

super()表示调用父类中的构造方法

1、子类继承父类,子类的构造方法的第一行,系统会默认编写super(),在调用子类的构造方法时,先调用父类的无参数构造方法

2、如果父类中只有有参数构造方法,那么子类继承父类时会报错,因为子类的构造方法在默认调用父类无参数构造方法super()不存在。

3.如果子类的第一行编写了this()、this(实参),因为this()也会占用第一行,所以此时就会将super()挤掉,就不会调用父类构造方法。

实例1.子类的构造方法会默认在第一行先调用父类无参数构造方法super()

//父类
public class Father
{

    int id;
    
    public Father()
    {
        System.out.println("调用父类中的构造方法");
    }
}

//子类
public class Son extends Father
{
    public Son()
    {
        System.out.println("调用子类构造方法");
    }

}

//测试类
public class Test
{
    public static void main(String[] args)
    {
        Son s = new Son();
    }

}

//结果是:先调用父类无参数构造方法,在调用子类构造方法
 

 实例2:父类中没有参数构造方法

//父类中编写有参数构造方法,覆盖无参数构造方法
public class Father
{

    int id;
    //定义有参数构造方法
    public Father(int id)
    {
        System.out.println("调用父类中的构造方法");
    }
}

//子类继承父类
//因为父类中没有无参数构造方法,所以会子类继承父类时会报错
 

 我们可以通过在子类中调用父类有参数构造方法来避免这种错误,

//定义父类,并且编写有参数构造方法覆盖无参数构造方法
public class Father
{

    int id;
    
    //编写有参数构造方法覆盖无参数构造方法
    public Father(int id)
    {
        System.out.println("调用父类中的构造方法");
    }
}


//定义子类
public class Son extends Father
{
    public Son()
    {

               //在构造方法中调用父类有参数构造方法
        super(10);
        System.out.println("调用子类构造方法");
    }

}

//编写test类

public class Test
{
    public static void main(String[] args)
    {
        Son s = new Son();
    }

}

测试结果:
 

 也可以在构造方法中调用本类中其他构造方法,来挤掉super()调用父类中无参数构造方法

//父类
public class Father
{

    int id;
    
    //
    public Father(int id)
    {
        System.out.println("调用父类中的构造方法");
    }
}

//子类
public class Son extends Father
{
    //无参数构造方法
    public Son()
    {
        //手动编写调用父类有参数构造方法
        super(10);
        System.out.println("调用子类构造方法");
    }
    
    //有参数构造方法
    public Son(int i)
    {
        //调用本类其他构造方法,挤掉super()
        this();
        System.out.println();
    }

}
原文地址:https://www.cnblogs.com/jesse-zhao/p/10660533.html