0

I have a number of classes that define a method, and I want to execute some code (say, some "prologue" and "epilogue") around that method:

public interface Thing {
    public void stuff();
    public void callStuff();
}
public abstract class Something implements Thing {
    public abstract void stuff();
    public void callStuff() {
        ... // common prologue
        //try {
            stuff();
        //} finally {
            ... // common epilogue
        //}
    }
}
public class A extends Something {
    public void stuff() { ... }
}
public class B extends Something {
    public void stuff() { ... }
}
public class Wrapper extends Thing {
    private Thing t;
    Wrapper(Thing thing) { t = thing; }
    public void stuff() { t.stuff(); }
    public void callStuff() { t.callStuff(); }
}

// Use:
Something s = ...;
s.callStuff();

You see that the idea is that subclasses will redefine stuff() while the clients will invoke callStuff(). Nevertheless, in some rare cases one has to call stuff(), see Wrapper above.

Something like that we see in the Thread class (since JDK 1.0), child classes redefine run() but the clients invoke start().

How do I prevent clients from calling stuff() directly?

EDIT

protected does not work here because the "clients" really are children of Something coded by another team. @Deprecated would work, but stuff() is not really deprecated, and everyone knows what "deprecated" is, so I cannot redefine the meaning of @Deprecated.

Ideally, the compilation should fail unless an explicit directive is given to ignore the problem.

18446744073709551615
  • 16,368
  • 4
  • 94
  • 127

0 Answers0