Reputation: 78525
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
Reputation: 4623
Mark it final
inside you abstract class (in Java). No other subclass will be allowed to override it.
Upvotes: 1
Reputation: 95488
Mark the method as final
, which prevents overriding:
public final void mainBit()
Upvotes: 3
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