子类和父类构造方法的执行先后问题

来源:互联网 发布:js case when 多条件 编辑:程序博客网 时间:2024/05/15 08:39

在java中如果一个类中没有显式的使用super()进行调用超类的构造方法,则在执行子类构造方法之前会首先待用父类的构造方法,如下:

/** * Created by zhuxinquan on 15-11-24. */class Circle{    double radius = 10;    public Circle(){        //this(0);        System.out.println("Parent radius"+radius);    }    public Circle(double r){        radius = r;        System.out.println("Parent radius"+radius);    }}class Cylinder extends Circle{    double height = 100;    public Cylinder(){        System.out.println("height"+height);    }}public class Ex5_5 {    public static void main(String[] args){        Cylinder obj = new Cylinder();        System.out.println(obj.radius);    }}

在Cylinder类中没有显式的调用super(),则在声明Cylinder类时,首先会调用超类的构造方法,在执行完成超类的构造方法之后再会执行本类的构造方法,就会产生如下的结果:
Parent radius10.0
height100.0
10.0

1 0