0

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?

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by mark185
0

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.

Edited by masijade: n/a

0

> 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();
  }
}
0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.