Possible Duplicates:
Interface vs Base class
When should I choose inheritance over an interface when designing C# class libraries?
So I'm writing my first real program in C#. The program will scrape data from four different websites. My plan is to have one parent class that will look like this:
class Scraper { string scrapeDate(url); string scrapeTime(url); //&c. }
Then I will have four classes that inherit from it.
The other option is to make Scraper
an interface and have four classes implementing it.
What are the differences between these approaches?
Inheritance is the mechanism in java by which one class is allowed to inherit the features of another class. Interface is the blueprint of the class. It specifies what a class must do and not how.
Interfaces allows to define the structure of common behaviors. Inheritance is useful if you can extract a common implementation of one or more specific behaviors.
If whatever you choose don't matter, always choose Interface. It allows more flexibility. It might protect you from future changes (if you need to change something in the base class, the inherited classes might be affected). It also allow to encapsulate the details better.
Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.
Class inheritance represents an "is-a" relationship, e.g., a Tank
is a Vehicle
. If your situation doesn't at least meet this, choose interface over inheritance.
If the proposed base class doesn't provide default implementations for your methods, this would be another reason to choose interface over inheritance.
In C#, you can only inherit from one class but multiple interfaces. This would be yet another reason to choose interface over inheritance.
Get the idea?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With