Calling super()

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

    Because the super class' constructor is not called automatically. There might, for example, be several constructors, some of which take additional parameters. So you do not always have got an "empty" super() statement, but something like this:

    public class DerivedClass extends SomeOtherClass
    {
       private String anotherParameter;
       public DerivedClass(int parameterA, String parameterB, String anotherParameter)
       {
         super(parameterA, parameterB);
         this.anotherParameter = anotherParameter;
       }
    }
    

    Edit: I obviously forgot to say (or my choice of words simply wasn't good, but I'm no native speaker, sorry for that) that if the super class does not take any parameters, the call to super() will be done for you by java/the compiler. (Now that I re-read my answer, I can see that it really sounds like you would always have to call super().)

提交回复
热议问题