Identify the problem in the below code:

Description:

public class Foo {
    public Foo() {
        doSomething();
    }

    public void doSomething() {
        System.out.println("do something acceptable");
    }
}

public class Bar extends Foo {
    public void doSomething() {
        System.out.println("yolo");
        Zoom zoom = new Zoom(this);
    }
}

Solution:

Classic example for escaping references.

When an object of Bar is created, the super constructor in Foo gets called first, which in turn calls the ‘overridden’ doSomething method.

The doSomething method passes the this instance to the class Zoom. Zoom now can use the ‘this‘ instance before it is created entirely.

0 answers