Calling super()

后端 未结 12 1055
孤独总比滥情好
孤独总比滥情好 2020-12-01 12:24

When do you call super() in Java? I see it in some constructors of the derived class, but isn\'t the constructors for each of the parent class called automatically? Why woul

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 12:45

    I wanted to provide some information that hasn't been mentioned so far. If you use a call to this(...) in a constructor, then you can't have a call to super(...); This also includes Java's automatic insertion of the parameterless call to super();

    The following example illustrates this point, including explanatory comments:

    public class B extends A {
        private int x;
    
        public B() {
            // Java doesn't call super(); here, because 
            // of the call to this(...); below.
            // You can't call super(...) here either,
            // for the same reason.
    
            this(42);  // Calls public B(int x) below.
        }
    
        public B(int x) {
            // Java does call super(); here.
            // You can call super(...) here, if you want/need to.
            // The net result of calling new B() above is that
            // super(...) for class A only gets called once.
    
            this.x = x;
        }
    }
    

提交回复
热议问题