super() in Java

前端 未结 15 1990
逝去的感伤
逝去的感伤 2020-11-22 05:36

Is super() used to call the parent constructor? Please explain super().

15条回答
  •  有刺的猬
    2020-11-22 06:01

    The super keyword can be used to call the superclass constructor and to refer to a member of the superclass

    When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.

    At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.

    public class Box {
    
        int width;
        int height;
        int depth;
    
        Box(int w, int h, int d) {
            width = w;
            height = h;
            depth = d;
        }
    
        public static void main(String[] args){
            HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
        }
    
    }
    
    class HeavyBox extends Box {
    
        int weight;
    
        HeavyBox(int w, int h, int d, int m) {
    
            //call the superclass constructor
            super(w, h, d);
            weight = m;
        }
    
    }
    

提交回复
热议问题