My Audio Blog for this page here
Abstract Classes :
Abstract classes are the classes that cannot be instantiated. They cannot have objects but they serve as a tool to maintain some hierarchical structure in the program. These classes can contain methods which may contain or may not contain definition. But there should be at-least one undefined method. The class can contain member variables also.
Abstract classes helps in aggregating the classes of similar type to have a single base class. For example , a squirrel and a human can be very different in nature but by classification they belong to the same abstract class of Animals as they have common behavior.
Class Animals{
see(){use eyes to watch ;}
hear() {use ears to hear;}
move(){}=0;
}
Class Man : Animals{
move(){use two legs;}
}
Class Squirrel : Animals{
move(){use four legs;}
}
Abstract class will have the basic behavior of all the classes inherited from it. The user can inherit the abstract classes and add additional behavior he wants to his new class.
Interface :
Interfaces seem to be similar to Abstract Classes but they are not allowed to define anything inside them. They are just to list the set of methods which must be implemented in the class which implements the interface. They are to support multiple inheritance.
Multiple inheritance are not supported in java and C#. So programmers come up with interfaces to handle this. A class can have not more than one parent class , but it can have any number of interfaces. The iphone has both the qualities of a connecting device and a computer. So we may design the model like this,
interface connecting_device{
make_call();
get_call();
}
Class computer{
use_browser();
use_applications();
watch_movies(){use a player to run the movie on screen};
store_info();
}
Class iphone: extends computer , implements connecting_device{
make_call(){....}
get_call(){....}
store_info(){....}
}
Class nokia_1100: implements connecting_device{
make_call(){...}
get_call(){...}
}
In case where you need a class which has more than a behavior we categorize it in a single domain and use interface to attain the rest of the behavior.
Abstract vs Interface :
The users may confuse as when to go for Interface and when to go for Abstract class. They have some similarities as they cannot be instantiated and contain undefined functions. But Interface is not a class.
It all depends on the way you look at your problem. But my best advice would be to look for any common behavior in the objects. If they exist make a abstract class and define the common behavior within the class and inherit the classes from the abstract class.
Partial Classes:
Partial classes is a new concept in C#. Using partial classes we can split the classes into multiple files.Compiler will treat them as different classes but when compiled they execute as a single class.
No comments:
Post a Comment