James Andrew Smith
James Andrew Smith

Reputation: 1568

Override empty methods in inheritance

Need a bit of OOP help.

I have a base payment consisting of SendPayment() UpdateRecord() then child classes implementing different payment formats e.g. PayPal, SagePay.

While all have SendPayment() method they are all implemented differently. So I override the base class to apply my own implementation in each child class. The base classes do not hold any implementation just empty methods. Is this a good way of OOP to have empty methods then implement override code in each child class or remove the empty methods in the base and have these methods in the child classes?

thanks...

Sorry a quick edit. I do use the base class for certain scenarios for example calculation. This covers all payment types such as counting how many products by the cost and removing records from the table.

Upvotes: 3

Views: 3890

Answers (3)

petro.sidlovskyy
petro.sidlovskyy

Reputation: 5103

It's OK. But it depends on how would you use the base class. You may mark methods or class abstract and in this case all child classes MUST implement them. If you mark them as virtual child classes may override them if required or leave empty.
If you don't specify methods in base class you won't be able to use abstraction and polymorphism with all it power. For example if you have list of Payments (List<Payment>) (doesn't matter what actual type of payment is) and you want to send all of them you won't be able to do next:

foreach(Payment payment in payments)
{
   payment.SendPayment();
}

Upvotes: 0

Yogendra Singh
Yogendra Singh

Reputation: 34367

I would suggest to make your base class as abstract class and make the unimplemented method as abstract method.

    public abstract class BasePayment {

        //abstract method: unimplemented        
        public abstract void sendPayment();

        //implemented method    
        public void UpdateRecord(){
            .....
        }

    }

Abstract class is meant for this kind of scenarios where you want to have mix of implemented and unimplemented method. One added advantage here is: Every extending class will be forced to implement its own sendPayment method.

Upvotes: 4

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50752

If your child classes doesn't have meaning without overriding base methods, keep base methods abstract.

But if base class contains only abstract methods, and doesn't have any state(which is your case I guess) is is better to use interface, because interface leave implementer right to have another base class

Upvotes: 2

Related Questions