Shehryar Shehryar - 2 months ago 9
Java Question

Doing Java Problems and can't understand what this statement means

I'm solving random online java problems. I'm stuck with an OOP problem. The statement is


This second constructor should create Move[] objects and pass to the
third constructor.


What is meant by this? According to my rudimentary knowledge, we can't create new objects within a constructor, can we?

Answer

Consider this example:

class Foo {
    Foo(Bar[] bars) {
        ...
    }
}

We can make another ctor call Foo(Bar[] bars) by writing this(...) as the first line:

class Foo {
    Foo() {
        this(new Bar[]{});
    }
    Foo(Bar[] bars) {
        ...
    }
}