Why must the use of the this keyword, or similarly the use of the super keyword in constructor chaining, be on the first line of an overloaded constructor?

In other words, actual class construction cannot be split between constructors. If re-direction must occur, it must be the first line of a constructor. Why?

If you want to "split up" the initialisation, place the actual processes into private methods and call those methods from the constructors, rather than coding it directly into the constructors.

And "private" is not a mistake. The methods must be either private or final (or both, although that is overkill) to prevent any unintended consequences from any possible polymorphish.

> If re-direction must occur, it must be the first line of a constructor. Why?

To ensure that the parent class is completely initialized before it gets used in the child class's constructor body. If this restriction was not imposed, you could have code like this which really doesn't make sense:

public class A {}
public class B {
  public B() {
    // How do you expect to access something before it is contructed?
    Class c = super.getClass();
    super();
  }
}

Thank you for this example...it makes sense to me know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.