Ada
Ada

Reputation: 1

Why this() is not allowed in void method?

I’m creating class A with public void A() method that has this() as a first statement. A() method is obviously not a constructor, but compiler complains about this() not being a first statement of some constructor which, I believe, is implicitly created with super() as a first statement. What constructor and what this() statement does the compiler refer to? Thank you.

class A
{
    public void A(){this();}
}

Output error: call to this must be first statement in constructor public void A(){this();} ^ 1 error

Upvotes: 0

Views: 131

Answers (1)

Dishonered
Dishonered

Reputation: 8841

super() refers to the constructor of the parent class and this() refers to the constructor of the subclass. You cannot use this() anywhere except in a constructor of a different signature and only as the first statement.For example this is valid.

          A(int x){
              this(); // Calling a no argument constructor of the same class
          }

But this is invalid , it throws a compilation error because this is recursive construuctor invocation.

          A(){
             this();
          }

You cannot use this() in methods.

Upvotes: 2

Related Questions