Pergunta

I am new to Java programming, but have some basic understanding. Here is my question, i have a base class and many classes extends this base class. In some cases, after a standard action performed by the base class method , i need to do some action only for some sub classes. So i just done as in the following way. Just want to check i am right as per OOPS

class BaseClass {

    public void deleteThisRecord() {
        // All standard code goes here
        doSomethingAfterDelete(); // call clean up method after sucessful delete
    }   

    public void doSomethingAfterDelete() {
        // Nothing is here, let the sub class override this if there is need
    }
}

class OneClass extends BaseClass {
    // other methods

    @Override
    public void doSomethingAfterDelete() {
        // do some action after delete
    }
}
Foi útil?

Solução

Yes, this will work in the way that you describe, in that derived classes can choose to implement doSomethingAfterDelete() or not. However, in Java, all methods of a base class can be overridden by default in the derived class, so you may like to add the final modifier to your method deleteThisRecord() to prevent it being overridden:

public final void deleteThisRecord() {
    // All standard code goes here
    doSomethingAfterDelete(); // call clean up method after successful delete
}

Outras dicas

Abstract methods are placeholder methods that can only be called from the subclass. I suggest that if doSomethingAfterDelete() is an empty placeholder method intended to be overridden, you should write it as:

public abstract void doSomethingAfterDelete();

and then in the subclass, override it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top