-4

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
    }
}
Chris Mantle
  • 6,595
  • 3
  • 34
  • 48
Senthil Muthiah
  • 97
  • 1
  • 3
  • 14
  • This will work if the base class has a default implementation, and you want some subclasses to change. If you want the sub class to be forced to have it you may want to think about using abstract classes – dbarnes Oct 31 '13 at 17:05
  • 5
    This question is more on-topic for http://codereview.stackexchange.com/ but to give you my opinion there is nothing illegal about doing this. I do it sometimes since it is slightly more flexible than abstract methods. Sometimes I only want _some_ of the subclasses to do something. – Radiodef Oct 31 '13 at 17:07
  • You probably should make `deleteThisRecord()` **final** so the subclass do not implement it again without the call to `doSomethingAfterDelete()`. – SJuan76 Oct 31 '13 at 17:07

2 Answers2

1

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.

La-comadreja
  • 5,627
  • 11
  • 36
  • 64
1

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
}
Chris Mantle
  • 6,595
  • 3
  • 34
  • 48