0

I want to implement an Abstract Java class. One of the abstract methods must be implemented by each child class, to ensure that that part of the code will be executed individually in each child class. Is there any other way to do it and thus avoid the "warning" that appears by calling an abstract method from the constructor of the main class?

    public abstract class Listener {

    protected Date checkTime = new Date();
    protected TypeUpdate type = UNKNOW;

    public Listener(){
        super();
        this.setTypeListener();
    }

    public void setTime(Date date) {
        if (date != null) {
            return;
        }
        this.checkTime = date;
    }

    /* Abstract methods */
    public abstract void execute();

    protected abstract void setTypeListener();
    }

Thank you. ------------------------------ EDITED ----------

Ok, It's an error call an abstract method in constructor. So, what can I do to force inheriting classes to make a concrete constructor implementation (for example, initialize a member in one way or another?)

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
  • Question is not clear. Are you trying to avoid a warning? – Kris Mar 05 '20 at 11:18
  • 3
    You should read [What's wrong with overridable method calls in constructors?](https://stackoverflow.com/questions/3404301/whats-wrong-with-overridable-method-calls-in-constructors) – Guy Mar 05 '20 at 11:22
  • Why are you calling super in your constructor? – jpuriol Mar 05 '20 at 11:22
  • Thank you for your fast replies. Super is not important, I can remove it, just same the same warning. Yes, im trying to avoid the warning. Reading your link, ty. –  Mar 05 '20 at 11:24
  • Ok, so, what can I do to force a subclass to inicialize a member class with a value? –  Mar 05 '20 at 11:29
  • @radel2010 to force the some value to be specified, you should have parameter in constructor. Can you use that in your case? If not, why? – Betlista Mar 05 '20 at 11:33

1 Answers1

0

You are arriving in the base class constructor and on returning from that constructor, in the child class constructor all field initialisations will happen and the remaining code form the child constructor.

To ensure that some method is called you can either call that method lazily later. Or pass an independent object, as "part" of the entire child.

public Child() {
    super(createPart());
}

private static Part createPart() {
    return new Part().withAnswer(42);
}

public Base(Part part) { ... }

One may also have a case of

  • service offered (public final)
  • requirement implemented (abstract protected)

So:

class Base {

     public final void foo() {
         onFoo();
     }

     protected void onFoo() {
         throw new IllegalStateException("Missing onFoo implementation "
             + getClass().getName());
     }
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138