pedrorijo91
pedrorijo91

Reputation: 7845

Java method that can't be callable but can be overridden

If I don't want that a method on my class can be called, I just make it private.

But if I want to allow that method to be overridden, I have to make it protected

Is it possible to have a method on an abstract class that can't be called but can be overridden? (I guess not, but is there any workaround?)

Use case:

abstract class Super {

  protected void finalize() {

  }

  public final void doThings() {
   // do stuff
   finalize();
  }
}

and whoever wanted to extend the class:

class Sub extends Super {

  @Override
  protected void finalize() {
    closeSockets();
    alertSomeone();
  }

}

But I don't want other classes calling mySub.finalize();

Upvotes: 0

Views: 529

Answers (1)

DudeDoesThings
DudeDoesThings

Reputation: 729

Instead of overwriting a method, the sub-class may provide the super-class with a Runnable which contains the code to be executed. You could do something like this:

public class Super {

    private final Runnable subClassCode;

    public Super(Runnable finalizeCode) {
        subClassCode = finalizeCode;
    }

    public final void doThings() {
        // do stuff
        subClassCode.run();
    }

}

public class Sub extends Super {

    public Sub() {
        super(() -> {
            // code to be executed in doThings()
        });
    }

}

You dont need to set the Runnable instance in the constructor. You may also give access to a protected setFinalizeCode(Runnable) method but that method could also be called by other classes within the same package as Super.

Upvotes: 2

Related Questions