What I would like to know is, if I have a superclass: A and a subclass B with a particular method in A and that method is overriden in B.
Lets say that A has a certain function...maybe to paint text. How can I guarantee that this function is always called, and that it cannot be changed in
the overriden classes?
Inside your overridden method in your subclass B, call "super.methodName()", this will call the method in your super class. Now when you call your method in the subclass it will always execute the method in your super class.
Certified JA, JP5, WCD5, BCD6
posted 11 years ago
Hi thanks very much for your response. However, what I meant to say but I forgot was: Assume that I want this method to be executed ALWAYS, AND, assume that someone else has access to my subclasses. They will override my method, but how can I still guarantee that a particular command called in the superclass' method is called, regardless if they change the implementation in the subclass.
What you're looking for here is the template design pattern. You would like the super always to be executed and the additional subclass specific steps to be executed. It's actually an anti-pattern to force the user to call super.methodName() when you don't need to for the problems you are seeing. If this is a required method, you don't want to leave it up to the user to forget (accidentally or maliciously). Some sample code is below. A client will call methodName() which will call the SuperClassA implementation and then methodNameImpl() which is implemented by SubClassB.
Note: If you want SuperClassA to be able to be instantiated directly, you should remove the abstract and give methodNameImpl an empty implementation in SuperClassA. Then no extra behavior will be executed if you use SuperClassA, and optionally, subclasses can override for specific additional behavior.