Monday, March 26, 2012

OOP realated issue

why bother to include method in super class.

if we have to implement methods in sub class .

Each of the subclass simply override the method anyway.

I know answer lies in polymorphism but what is the advantage.

Hi,

why do you override the methods in each subclass? If so maybe it's better to delete the base class and use an interface instead so that each class has to implement the methods defined in the interface and you can use the type of the interface as input parameter, for example, for a method to pass in all possible types that implement that interface.

Grz, Kris.


If you are overriding in each and every sub class, then essentially, your base class method means nothing. Might as well get rid of it. The purpose of having a super class method is to provide the needed implementation if sub class doesn't provide one on its own. Interface - meaning a "contract" that all your class has to stick to will be a better approach.

One example of super class method can be something like Sorting(). By defeault, it uses a bubble sort. However, one f my sub classes used by another part of the application requires very quick sorting algorithem because it'll do a lot of computations, so our smart computer science guy remembered his lessons from his algorithm class and implemented the "Sorting()" by using quicksort. Most of other sub classes is fine with bubble sort because their data is really light, no need to bang themsevles to implement a fancy smancy algorithem. They stick with using the default Sorting(). So implementing this sturcture gives certain people the flexbility to do whatever they want without affecting others. Make sense?

That's just an example. We don't have such smart ppl here who decided to take up on himself to do a quick sort algorithem, but you get the idea.

Now, Interface is different. Take another example, the easiest one is the "IDBConnection" used by ADO.NET. Microsoft wants to support database vendor (sqlserver, mysql, oracle, whatever), but how to do you make sure everyone use the same syntax to open a connection to database and close the connection to database? You create an interface contract, so everyone agree to use ".open()" and ".close()" and not having someone go wild, say mysql do ".openMySql()" and oracle do ".openOracle()" as they are not interchangeable. As to exactly how mysql or oracle open a connection to their database, I imagine they are quite different in the background, makes sense to ask each of them to provide their specific implementation.

0 comments:

Post a Comment