super() in Java

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

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

15条回答
  •  死守一世寂寞
    2020-11-22 05:46

    Constructors
    In a constructor, you can use it without a dot to call another constructor. super calls a constructor in the superclass; this calls a constructor in this class :

    public MyClass(int a) {
      this(a, 5);  // Here, I call another one of this class's constructors.
    }
    
    public MyClass(int a, int b) {
      super(a, b);  // Then, I call one of the superclass's constructors.
    }
    

    super is useful if the superclass needs to initialize itself. this is useful to allow you to write all the hard initialization code only once in one of the constructors and to call it from all the other, much easier-to-write constructors.

    Methods
    In any method, you can use it with a dot to call another method. super.method() calls a method in the superclass; this.method() calls a method in this class :

    public String toString() {
      int    hp   = this.hitpoints();  // Calls the hitpoints method in this class
                                       //   for this object.
      String name = super.name();      // Calls the name method in the superclass
                                       //   for this object.
    
      return "[" + name + ": " + hp + " HP]";
    }
    

    super is useful in a certain scenario: if your class has the same method as your superclass, Java will assume you want the one in your class; super allows you to ask for the superclass's method instead. this is useful only as a way to make your code more readable.

提交回复
热议问题