SvetlanaRosemond SvetlanaRosemond - 1 month ago 4
Java Question

Trouble Understanding "Leaking the this reference"

I was reading about weather or not it's good practice to call a setter from the constructor on this SO page. I'm aware that you shouldn't call non-final methods from your constructor. One of the answers suggests:

Constructors should be cautious about leaking this before the instance
is fully initialized.

I don't fully understand what the above quote means. Suppose I have the following class:

public final class Employee
private String empID;
private String empFirstName;
private String empLastName;

public Employee(String ID, String FirstName, String LastName)
//Call to other setters left out.


//empID, empFirstName setter left out.
public void setEmployeeLastName(String lastname)
this.empLastName = lastname;

  1. Just as an example, how would I leak the this reference before the instance is fully created? Does it mean passing the object as an argument before it has been created?


Leaking this references can be dangerous because things that look like they should be fully initialized might not be, and that fact can be easily hidden. Here's an example of how it can be problematic using subclassing:

class Foo{
    void doStuff(){}

class Bar extends Foo{
    private int i = 1;
    public void doStuff(){

You'd think, when instantiating a new instance of Bar, that it would display 1. But instead it displays 0, because the method gets called before Bars constructor runs, and so i hasn't had its value set yet. This is one example of how a leaking this can backfire in code that otherwise looks fine.

For your second question, calling final or private methods is almost always valid in a constructor. The only exception is if you call a method that depends on some value being initialized, and the method is called before that initialization happens. But your setter doesn't depend on any state, so that's not the case, and it can't be modified in a subclass (since it's final) so there's no way for it to misbehave.