JackW
JackW

Reputation: 999

Call parent constructor with this as argument

I have a class that takes one of its subclasses as an argument. When constructing that subclass, I want to be able to use this as the value of that argument:

class A(val b: B)

class B extends A(this)

However, this fails to compile

this can be used only in a class, object, or template
[error] class B extends A(this)
[error]                   ^

Is there any way to get around this? I'm pretty sure that a pattern like this can be written in Java.

Upvotes: 1

Views: 47

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

I'm not so sure about the last statement:

public class MyClass {
    static class A {
        A(B b) {
            System.out.println(b.value);
        }
    }
    static class B extends A {
        String value;;
        B() {
            super(this);
            value = "x";
        }
    }
    public static void main(String args[]) {
        new B();
    }
}

gives the following error:

/MyClass.java:10: error: cannot reference this before supertype constructor has been called
            super(this);
                  ^

There is no good reason to attempt to let the this reference escape the scope of the constructor before the object itself has been constructed. Refactor it.

Upvotes: 2

Related Questions