Calling super()

后端 未结 12 1077
孤独总比滥情好
孤独总比滥情好 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:35

    You would need to use super() in a case like this:

    public class Base {
       public Base(int foo) {
       }
    }
    
    public class Subclass extends Base {
       public Subclass() {
          super(15);
       }
    }
    

    This is a very contrived example, but the only time that you need to call super() is if you're inheriting from a class that doesn't provided a default, parameterless constructor. In this cases you need to explicitly call super() from the constructor of your subclass, passing in whatever parameters you need to satisfy the base class's constructor. Also, the call to super() must be the first line of your inherited class's constructor.

提交回复
热议问题