0

If I have a superclass Animal with no attributes, and then another subclass Dog with one attribute, is it valid to use the super() method when creating the constructor for the subclass? Here's the example code:

public class Animal {
    
    public Animal() { }
}
public class Dog extends Animal {
    
    public int age;
    public Dog(int age){
        super(); // Do I include this?
        this.age = age;
    }
}

Is there any reason why I should or should not call the super() function in the Dog class, and does it make a difference? Thanks!

  • 1
    [this](https://stackoverflow.com/questions/2054022/is-it-unnecessary-to-put-super-in-constructor) could provide you an answer. But short answer is no, you don't have to. – christianfoleide Apr 17 '21 at 17:40
  • Unless you have to invoke some piece of code in super, you don't have to. – Raj V Jun 28 '21 at 16:03

2 Answers2

4

You don't need to call super() here as no-arg super class constructor gets called by default from subclass.

Only if there is a constructor in super class with some argument, then you need to call it from subclass explicitly if required.

aatwork
  • 2,130
  • 4
  • 17
  • 1
    You are only required to call `super` if there is *no no-arg constructor* in the superclass. There can be constructors in the superclass which take params, but it's fine if there is also a no-arg ctor. – Andy Turner Apr 17 '21 at 17:53
2

From the language spec:

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

This means that, if you don't have an explicit call or does have an explicit call to super(), the superclass needs to have a no-arg constructor - either an explicitly declared one, or a default constructor (a no-arg constructor automatically added by the compiler if the class has no other constructors).

As such, if the code compiles with the explicit super(), that means the super class does have a no-arg constructor: and so it would also compile and work equivalently if you omitted the super().

Andy Turner
  • 137,514
  • 11
  • 162
  • 243