Home » Java » java – How can I use newly-added constructor arguments of a class in an overridden method called during the superclass's constructor?-Exceptionshub

java – How can I use newly-added constructor arguments of a class in an overridden method called during the superclass's constructor?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

If I have a class Foo which calls a method like someMethod in its constructor, and I want to override someMethod to make use of constructor arguments which I have newly-added in this subclass, how can I do this?

Let’s suppose that Foo has a noargs constructor which calls someMethod. What I wish I could do is something like:

public class Bar extends Foo {
    private String x;
    private String y;
    public Bar(String x, String y) {
        this.x = x;
        this.y = y;
        super();
    }
    @Override
    public void someMethod() {
        // do stuff with x and y
    }
}

Of course, I can’t do that because Java insists that the call to the superclass constructor is on the first line of the subclass constructor. If I moved it to the first line then it would be called before x and y were initialised and therefore someMethod would not use their values as passed into my constructor.

It seems I can get around this using inner classes, but it’s pretty horrible.

public class Bar extends Foo {
    private String x;
    private String y;
    private Foo baz;
    public class Foobar extends Foo {
        @Override
        public void someMethod {
            // do stuff with Foo.this.x and Foo.this.y
        }
    }
    public Bar(String x, String y) {
        this.x = x;
        this.y = y;
        baz = new Foobar();
    }
    // override ALL of the remaining methods, including someMethod, delegating them to baz
}

This is a horrible solution, is this an accepted pattern and is there any better way?

NOTE: To clarify in case it’s not obvious, the class Foo is not under the developer’s control (e.g. it’s part of a third-party library). The developer is trying to extend Foo and so any design decisions made by Foo (e.g. non-final method called from constructor) are not things the developer can influence.

EDIT: People are asking in the comments if someMethod is private. It is not private, if it was then I wouldn’t be able to override it. Here is an example of said class Foo to illustrate:

public class Foo {
    public Foo() {
        // some other stuff...
        someMethod();
    }
    public void someMethod() {
        // nothing of consequence
    }
    // some other methods, which aren't relevant to the question
}
How to&Answers: