0

I am trying to construct a subclass like this

abstract class Foo
{
    abstract BiConsumer getConsumer();

    Foo(Object value)
    {
        getConsumer().accept(this, value);
    }
}

class Bar extends Foo
{
    Object value = SOME_OBJECT_1;

    @Override
    BiConsumer getConsumer()
    {
        return (object, value) -> ((Bar)object).setValue(value);
    }

    Bar()
    {
        super(SOME_OBJECT_2);
    }

    void setValue(Object value)
    {
        this.value = value;
    }
}

but using a HashMap to store different things to be initialized in different subclasses.

The problem is, when I do this, and run

System.out.println(((Bar)this).value);

after accepting the consumer in Foo's constructor, I get, as expected, SOME_OBJECT_2. However, when I run

System.out.println(this.value);

after the super call in Bar's constructor, I get SOME_VALUE_1.

Why is this and how can I solve it?

Here is my superclass for reference, and here and here are some examples of subclasses

TianCilliers
  • 35
  • 1
  • 4
  • 3
    You are leaking `this` in the constructor like there's no tomorrow. I would suggest you completely rethink this design. Whenever you see `this` as an argument to a method in a `ctor` - you are doing something **wrong**. – Boris the Spider Mar 20 '17 at 20:30
  • 2
    Your problem is that `Object value = SOME_OBJECT_1;` is part of `Bar`s constructor and therefore runs after `super(SOME_OBJECT_2);` but before all other statements in `Bar`s constructor – Thomas Kläger Mar 20 '17 at 20:32
  • 5
    And here, you are taking the [overridable method in a ctor anti-pattern](https://stackoverflow.com/questions/3404301/whats-wrong-with-overridable-method-calls-in-constructors) to some sort of incomprehensible extreme. – Boris the Spider Mar 20 '17 at 20:32

0 Answers0