Calling super()

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

    If you fail to call super in a constructor, then the compiler will add a no-argument super call as the parent constructor for the first line of the constructor body.

    So as in the previously posted code

    public class Foo
    {
    }
    

    or

    public class Foo
    {
      public Foo()
      {
      }
    }
    

    the compiler will generate code that aligns with the rules of Java. All objects are subclasses of java.lang.Object, so the compiler will compile it as if it was written

    // All classes extend Object.  This is Java, after all.
    public class Foo extends java.lang.Object
    {
      public Foo()
      {
        // When constructing Foo, we must call the Object() constructor or risk
        // some parts of Foo being undefined, like getClass() or toString().
        super()
      }
    }
    

    But if the super class doesn't have a constructor that matches the parameters, then you must call the appropriate non-matching super class constructor.

    public class LightBlue extends java.awt.Color
    {
      public LightBlue()
      {
        // There is no Color() constructor, we must specify the suitable super class
        // constructor.  We chose Color(int red, int green, int blue).
        super(172, 216, 230);
      }
    }
    

    Other times, perhaps there is a constructor that matches the signature of the sub class's constructor, but for whatever reason, you do not wish to pass the parameters directly to the super class constructor.

    public class HSVColor extends Color
    {
      public HSVColor(int hue, int saturation, int value)
      {
        super(...code converting HSV to Red...,
              ...code converting HSV to Green...,
              ...code converting HSV to Blue);
      }
    }
    

    If you neglect to explicitly specify the super class constructor, then the compiler adds in the default no-arg super class constructor. However, if that constructor doesn't exist, then the compiler will not compile the class, because it is unclear which of the exposed constructors is the correct one to call.

    It is a style consideration, but you may decide to always include the super() call. If you chose to do so, it will be because you want the remind the reader that the base class objects must be built as part of the sub class object, and you want to make the particular super class constructor explicit. Traditionally, an always included super() call is quite odd, since traditionally code is only typed out if it differs from "default" behaviour.

提交回复
热议问题