Home > database >  Can super() only be called from within the child class constructor? | Java
Can super() only be called from within the child class constructor? | Java

Time:09-22

So I understand that super() calls the constructor of the parent class and I have used it on multiple occasions. However, I have never used it outside of the constructor of the child class. Is it possible to call super() from outside the child class constructor? Since super only makes sense when it is attached to a derived class, can it be treated like a member function of the derived class? I initially had this problem while trying to call super using an object (Just experimenting).

Is it possible to do something like this?

class Animal {
    Animal() {
        System.out.println("Animal's constructor was called.");
    }
}

class Puppy extends Animal {
    Puppy() {
        System.out.println("Puppy's constructor was called.");
    }
}

public class Test {
    public static void main(String[] args) {
        Puppy pupper = new Puppy();
        pupper.super();
    }
}

CodePudding user response:

No, that is not possible, not outside of a constructor body.

The Java Language Specification § 8.8.7.1 says the following:

ExplicitConstructorInvocation:
  [TypeArguments] this ( [ArgumentList] ) ;
  [TypeArguments] super ( [ArgumentList] ) ;
  ExpressionName . [TypeArguments] super ( [ArgumentList] ) ;
  Primary . [TypeArguments] super ( [ArgumentList] ) ;

Here, within the constructor body (§ 8.8.7), super() is allowed, but nowhere else.

  • Related