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!
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()
.