CodingIntrigue
CodingIntrigue

Reputation: 78525

Prevent abstract implementation from overriding certain method

I have an interface called Worker which I want to expose so that the end-user can simply call:

Worker w = WorkerFactory.createInstance();
w.mainBit();

How can I prevent classes which extend my AbstractWorker class from providing their own implementation of the mainBit method?

This is the structure I have so far:

interface Worker {
    void mainBit();
}

class WorkerFactory {
    public static Worker createInstance() {
        return new WorkerImpl();
    }
}

abstract class AbstractWorker implements Worker {
    @Override
    public void mainBit() {
        this.doThing1();
        this.doThing2();
    }

    public abstract void doThing1();
    public abstract void doThing2();
}

class WorkerImpl extends AbstractWorker {
    @Override
    public void doThing1() {

    }

    @Override
    public void doThing2() {

    }

    @Override
    public void mainBit() {
        // I don't want classes to override this functionality
    }
}

Upvotes: 1

Views: 2453

Answers (5)

Andrei Nicusan
Andrei Nicusan

Reputation: 4623

Mark it final inside you abstract class (in Java). No other subclass will be allowed to override it.

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95488

Mark the method as final, which prevents overriding:

public final void mainBit()

Upvotes: 3

Silviu Burcea
Silviu Burcea

Reputation: 5348

If you want to always use the AbstractWorker's mainBit, make it final in this class. This way, the subclasses won't override it.

Upvotes: 2

zAlbee
zAlbee

Reputation: 1189

Use the final keyword.

public final void mainbit ()
...

Upvotes: 3

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

You can do that by making the method final.

Upvotes: 5

Related Questions