Allowing the this reference to escape

  1. It means calling code outside the class, and passing this.
    That code will assume that the instance is fully initialized, and may break if it isn’t.
    Similarly, your class might assume that some methods will only be called after the instance is fully initialized, but the external code is likely to break those assumptions.

  2. final methods cannot be overridden, so you can trust them to not pass this around.
    If you call any non-final method in the constructor for a non-final class, a derived class might override that method and pass this anywhere.
     
    Even when you call final methods, you still need to make sure that they are safely written – that they do not pass this anywhere, and that themselves don’t call any non-final methods.

Leave a Comment

tech