Class
A user-defined user-defined data structure that groups properties and methods. Class doesn’t occupies memory.
Object Instance of Class is called object. An object is created in memory using keyword “new”.
Difference between Struct and Class •
•
•
truct are !alue !alue type and are stored on stack" while Class are #eference type and are stored on heap. truct “do not support” inheritance" while class supports inheritance. $owe% er struct can implements interface. truct should be used when you want to use a small data structure" while Class is better choice for comple& data structure.
What is the difference between instantiating structures with and without using the new keyword? 'hen a structure is instantiated using the new keyword" a constructor constructor (no-argument (no-argument or custom" if pro%ided) is called which initiali*es the fields in the structure. 'hen a structure is instantiated without using the new keyword" no c onstructor is called. $ence" one has to e&plicitly initiali*e all the fields of the structure before using it when instantiated without the new keyword.
Encapsulation 'rapping up of data and function into a single unit is known as +ncapsulation.
Properties Attribute of object is called properties. +g,- A car has color as property. +g pri%ate string string m_Color; m_Color; /
public string string Color Color
{ get { return m_Color; return m_Color; } set { m_Color = value value; ; } }
Car 0aruti 1 new Car()/ 0aruti.Color1 “'hite”/ Console.'rite(0aruti.Color)/ Isn't it better to make a field public than providing its property with both set { } and get { } block? After all the property will allow the user to both read and modify the field so why not use public field instead? Motivate your answer Not always! Properties are not just to provide access to the fields; rather, rather, they are supposed to provide controlled access to the fields of our class. As the state of the class depends upon the values of its fields, using properties we can assure that no invalid (or unacceptable) value is assigned to the fields. g
pri%ate int age/ public int Age Age 2 get 2 return age/ 3 set 2
if(%alue 45 ,66) 77throw e&ception else age 1 %alue/ 3 3
this Keyword
+ach object has a reference “this” which points to itself. 8wo 8wo uses of o f this keyword.
o Can be used to refer to the current object. o It can also be used by one constructor to e&plicitly in%oke another constructor of the same class. +g, class tudent 2 pri%ate string name/ pri%ate int age/ tudent(string name" int age) 2 this.name 1 name/ this.age 1 age/ 3 3
+g class Circle 2 double &"y"radius/ Circle(double &)2 this(&"6",)/ 3 Circle(double &" double y)2 this(&"y",)/ 3 Circle(double &" double y" double radius)2 this.& 1 &/ this.y 1 y/ this.radius 1 radius/ 3 3
Constructor • • •
•
• •
A constructor is a special method whose task is to initiali*e the object of its class. It is special because its name is the same as the class name. 8hey do not ha%e return types" not e%en %oid and therefore they cannot return %alues. 8hey cannot be inherited" though a deri%ed class can call the base class constructor. Constructor is in%oked whene%er an object of its associated class is created. 9ote 8here is always atleast one constructor in e%ery class. If you do not write a constructor" C: automatically pro%ides one for you" this is called default constructor. +g class A" default constructor is A().
Static Members of the class "tatic #e#bers belong to the whole class rather than to individual object "tatic #e#bers are accessed with the na#e of class rather than reference to objects. g class $est % public int rollNo; public int #aths&ar's; public static int totalMathMarks;
class 8est;emo 2 public static %oid main() 2 8est stud, 1 new 8est()/ stud,.roll9o 1 ,/ stud,.maths0arks 1 <6/ stud.roll9o 1 / stud.maths0arks 1 <=/ Test.totalMathsMarks 1
stud,.maths0arks > stud.maths0arks/
3 3 Static Method of the class
0ethods that you can call directly without first creating an instance of a class. +g 0ain() 0ethod" Console.'rite?ine() ou can use static fields, #ethods, properties and even constructors which will be called before any instance of the class is created. As static #ethods #ay be called without any reference to object, you can not use instance #e#bers inside static #ethods or properties, while you #ay call a static #e#ber fro# a non*static conte+t. $he reason for being able to call static #e#bers fro# non*static conte+t is that static #e#bers belong to the class and are present irrespective of the e+istence of even a single object.
Static Constructor In C: it is possible to write a static no-parameter constructor for a class. uch a class is e&ecuted once" when first object of class is created. @ne reason for writing a static constructor would be if your class has some static fields or properties that need to be initiali*ed from an e&ternal source before the class is first used. +g Class 0yClass 2 static 0yClass() 2 !nitiali"ation Code for static fields and properties#
3 3 $inali"e%& 'ethod of Object class +ach class in C: is automatically (implicitly) inherited from the @bject class which contains a method inali*e(). 8his method is guaranteed to be called when your object is garbage collected (remo%ed from memory). Bou can o%erride this method and put here code for freeing resources that you reser%ed when using the object.
or e&le rotected o%erride %oid inali*e()
2 try 2 Console.'rite?ine(“;estructing @bjectD.”)/ 77put some code here. 3 finally 2 base.inali*e()/ 3 3
Destructor A destructor is just opposite to constructor. It has same as the class name" but with prefi& E (tilde). 8hey do not ha%e return types" not e%en %oid and therefore they cannot return %alues. destructor is in%oked whene%er an object is about to be garbage collected +g class person 2 77constructor person() 2 3
77destructor Eperson() 2 77put resource freeing code here. 3 3 What is the difference between the destructor and the $inali"e%& (ethod? When does the $inali"e%& (ethod get called? inali*e() corresponds to the .9et ramework and is p art of the ystem.@bject class. ;estructors are C:Fs implementation of the inali*e() method. 8he functionality of both inali*e() and the destructor is the same" i.e." they contain code for freeing the resources when the object is about to be garbage collected. In C:" destructors are con%erted to the inali*e() method when the program is compiled. 8he inali*e() method is called by the .9et #untime and we can not predict when it will be called. It is guaranteed to be called when there is no reference pointing to the object and the object is about to be garbage collected.
)arbage Collection •
•
•
Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a %ariable. .9et #untime performs automatically performs garbage collection" howe%er you can force the garbage collection to run at a certain point in your code by calling System.GC.Collect(). Ad%antage of Garbage collection It pre%ents programming error that could otherwise occur by incorrectly deleting or failing to delete objects.
Enu(eration +numeration impro%es code readability. It also helps in a%oiding typing mistake.
Concept of *eap and Stack ?ocal !ariables
Stack
ree 0emory (?arger 0emory Area than tack). Global !ariables rogram Instruction
*eap
Per(anent Storage area
8he rogram Instruction and Global and tatic %ariables are stored in a region known as permanent storage area and the local %ariables are stored in another area called stack# 8he memory space located between these two regions is a%ailable for dynamic memory allocation during e&ecution of program. 8his free memory region is called heap# 8he si*e of heap keeps on changing when program is e&ecuted due to creation and death of %ariables that are local to functions and blocks. 8herefore" it is possible to encounter memory “o%erflow” during dynamic allocation process.
+alue ,ype and -eference ,ype
A %ariable is %alue type or reference type is solely determined by its data type. +g int" float" char" decimal" bool" decimal" struct " etc are %alue types" while object type such as class" tring" Array" etc are reference type.
+alue ,ype As name suggest !alue 8ype stores “%alue” directly. or eg 77I and H are both of type int I 1 6/ H 1 I/ int is a %alue type" which means that the abo%e statements will results in two locations in memory. or each instance of %alue type separate memory is allocated.
tored in a tack. It ro%ides uick Access" because of %alue located on stack.
-eference ,ype As name suggest #eference 8ype stores “reference” to the %alue. or eg !ector J" B/ 77@bject is defined. (9o memory is allocated.) J 1 new !ector()/ 770emory is allocated to @bject. 77(new is responsible for allocating memory.) J.%alue 1 =6/ 77Initialising %alue field in a %ector class. B 1 J/ 77Koth J and B points to same memory location. 779o memory is created for B. Console.writeline(B.%alue)/ 77displays =6" as both points to same memory B.%alue 1 L6/ Console.writeline(J.%alue)/ 77displays L6. 9ote If a %ariable is reference it is possible to indicate that it does not refer to any object by setting its %alue to null/ #eference type are stored on $eap. It pro%ides comparati%ely slower access" as %alue located on heap. ref keyword
assing %ariables by %alue is the default. $owe%er" we can force the %alue parameter to be passed by reference. 9ote %ariable “must” be initiali*ed before it is passed into a method. out keyword
out keyword is used for passing a %ariable for output purpose. It has same concept as ref keyword" but passing a ref parameter needs %ariable to be initiali*ed while out parameter is passed without initiali*ed. It is useful when we want to return more than one %alue from the method.
9ote Bou must assigned %alue to out parameter in method body" otherwise the method won’t compiled.
.o/ing and 0n1.o/ing Ko&ing means con%erting %alue-type to reference-type. +g int I 1 6/ string s 1 I.8oting()/ MnKo&ing means con%erting reference-type to %alue-type. +g int I 1 6/ string s 1 I.8otring()/ 77Ko& the int int H 1 Con%ert.8oInt=(s)/ 77MnKo& it back to an int. 9ote erformance @%erheads due to bo&ing and unbo&ing as the bo+ing #a'es a copy of value type fro# stac' and place it inside an object of type "yste#.bject in the heap.
!nheritance $he process of sub*classing a class to e+tend its functionality is called -nheritance. -t provides idea of reusability. Order of Constructor e/ecution in !nheritance
constructors are called in the order from the top to the bottom (parent to child class) in inheritance hierarchy. Order of Destructor e/ecution in !nheritance
$he destructors are called in the reverse order, i.e., fro# the botto# to the top (child to parent class) in the inheritance hierarchy.
hat are Sealed !lasses in !"? $he sealed #odifier is used to prevent derivation fro# a class. A co#pile*ti#e error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class) !an you prevent your class from being inherited by another class? es. $he 'eyword sealed/ will prevent the class fro# being inherited.
!an you allow a class to be inherited# but prevent the method from being over$ ridden? es. 0ust leave the class public and #a'e the #ethod sealed.
$ast $acts of !nheritance &ultiple inheritance of classes is not allowed in 12. -n 12 you can i#ple#ents #ore than one interface, thus #ultiple inheritance is achieved through interface. $he bject class defined in the "yste# na#espace is i#plicitly the ulti#ate base class of all the classes in 12 (and the .N$ fra#ewor') "tructures (struct) in 12 does not support inheritance, it can only i#ple#ents interfaces.
Poly(orphis( olymorphism means same operation may beha%e differently on different classes. +g 0ethod @%erloading is an e&le of Compile 8ime olymorphism. 0ethod @%erriding is an e&le of #un 8ime olymorphism Does C2#net supports (ultiple inheritance?
9o. A class can inherit from only one base class" howe%er a class can implements many interface" which ser%ers some of the same purpose without increasing comple&ity. *ow (any types of 3ccess 'odifiers#
,) ublic N Allows the members to be globally accessible. ) ri%ate N ?imits the member’s access to only the containing type.
=) rotected N ?imits the member’s access to the containing type and all classes deri%ed from the containing type. <) Internal N ?imits the member’s access to within the current project.
'ethod O4erloading 0ethod with same name but with different arguments is called method o%erloading. 0ethod @%erloading forms compile-time polymorphism. +g class A, 2 %oid hello() 2 Console.'rite?ine(“$ello”)/ 3 %oid hello(string s) 2 Console.'rite?ine(“$ello 263”"s)/ 3 3
'ethod O4erriding 0ethod o%erriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass. 0ethod o%erriding forms #un-time polymorphism. 9ote Ky default functions are not %irtual in C: and so you need to write “%irtual” e&plicitly. 'hile by default in Ha%a each function are %irtual. +g, Class parent 2 4irtual %oid hello()
2 Console.'rite?ine(“$ello from arent”)/ 3 3 Class child parent 2 o4erride %oid hello()
2 Console.'rite?ine(“$ello from Child”)/ 3 3 static %oid main() 2 parent objarent 1 new child()/ objarent.hello()/ 3 77@utput $ello from Child.
+irtual 'ethod Ky declaring base class function as %irtual" we allow the function to be o%erridden in any of deri%ed class. +g Class parent 2 4irtual %oid hello()
2 Console.'rite?ine(“$ello from arent”)/ 3 3
Class child parent 2 o4erride %oid hello()
2 Console.'rite?ine(“$ello from Child”)/ 3 3 static %oid main() 2 parent objarent 1 new child()/ objarent.hello()/ 3 77@utput $ello from Child.
osted by ;ot9etGuts at O< 0 6 comments
'onday5 'ay 65 7886 Concept of !nterface What is !nterface • • • •
An Interface is a group of constants and method declaration. .9et supports multiple inheritance through Interface. Interface states “what” to do" rather than “how” to do. An interface defines only the members that will be made a%ailable by an implementing object. 8he definition of the interface states nothing about the implementation of the members" only the parameters they take and the types of %alues they will return. Implementation of an interface is left entirely to the implementing class. It is possible" therefore" for different objects to pro%ide dramatically different implementations of the same members.
•
•
•
E/a(ple9 " the Car object might implement the I;ri%able interface (by con%ention" interfaces usually begin with I)" which specifies the Goorward" GoKackward" and $alt methods. @ther classes" such as 8ruck" Aircraft" 8rain or Koat might implement this interface and thus are able to interact with the ;ri%er object. 8he ;ri%er object is unaware of which interface implementation it is interacting with/ it is only aware of the interface itself. E/a(ple7 " an interface named Ihape" which defines a single method CalculateArea. A Circle class implementing this interface will calculate its area differently than a Puare class implementing the same interface. $owe%er" an object that needs to interact with an Ihape can call the CalculateArea method in either a Circle or a Puare and obtain a %alid result. Practical E/a(ple
public interface I;ri%able 2 %oid Goorward(int peed)/ 3 public class 8ruck I;ri%able 2 public %oid Goorward(int peed) 2 77 Implementation omitted 3 3 public class Aircraft I;ri%able 2 public %oid Goorward(int peed) 2 77 Implementation omitted 3 3 public class 8rain I;ri%able 2 public %oid Goorward(int peed) 2 77 Implementation omitted 3 3
E/tra • •
+ach %ariable declared in interface must be assigned a constant %alue. +%ery interface %ariable is implicitly public" static and final.
• •
•
•
+%ery interface method is implicitly public and abstract. Interfaces are allowed to e&tends other interfaces" but sub interface cannot define the methods declared in the super interface" as sub interface is still interface and not class. If a class that implements an interface does not implements all the methods of the interface" then the class becomes an abstract a bstract class and cannot be instantiated. Koth classes and structures can implement interfaces" including multiple interfaces.
osted by ;ot9etGuts at 6< 0 6 comments
'aking choice between !nterface and 3bstract Class In which Scenario you will go for Interface or Abstract !lass? -nterfaces, li'e classes, define a set of properties, properties, #ethods, and events. 3ut unli'e classes, interfaces do not provide i#ple#entation. $hey are i#ple#ented by classes, and defined as separate entities fro# classes. ven though class inheritance allows your classes to inherit i#ple#entation fro# a base class, it also forces you to #a'e #ost of your design decisions when the class is first published. Abstract classes are useful when creating co#ponents because they allow you specify an invariant level of functionality in so#e #ethods, but leave the i#ple#entation of other #ethods until a specific i#ple#entation of that class is needed. $hey also version well, because if additional functionality is needed in derived classes, it can be added to the base class without brea'ing code.
osted by ;ot9etGuts at 6 0 6 comments
Difference between !nterface and 3bstract Class !nterfaces 4s# 3bstract Classes
%eature Multiple inheritance
Interface
Abstract class
A class #ay i#ple#ent several several interfaces.
A class #ay e+tend only one abstract class.
An interface cannot &efault provide any code at all, implementation #uch less default code.
An abstract class can provide provide co#plete code, default code, and4or just stubs that have to be overridden.
1onstants
$hird party convenience
"tatic final constants only, can use the# without 5ualification in classes that i#ple#ent 3oth instance and static the interface. n the constants are possible. 3oth other paw, these static and instance intialiser un5ualified na#es pollute code are also possible to the na#espace. ou can co#pute the constants. use the# and it is not obvious where they are co#ing fro# since the 5ualification is optional. An interface i#ple#entation #ay be added to any e+isting third party class.
A third party class #ust be rewritten to e+tend only fro# the abstract class.
An abstract class defines the -nterfaces are often used core identity of its descendants. to describe the peripheral -f you defined a 7og abstract abilities of a class, not its class then 7a#a#ation central identity, e.g. an Is$a vs $able or descendants are 7ogs, they are Auto#obile class #ight can$do not #erely dogable. i#ple#ent the 6ecyclable -#ple#ented interfaces interface, which could enu#erate the general things a apply to #any otherwise class can do, not the things a totally unrelated objects. class is.
Plug*in
ou #ust use the abstract class as*is for the code base, with all its attendant baggage, good or bad. $he abstract class author ou can write a new has i#posed structure on you. replace#ent #odule for 7epending on the cleverness of an interface that contains the author of the abstract class, not one stic' of code in this #ay be good or bad. co##on with the e+isting Another issue that9s i#portant is i#ple#entations. 8hen what - call :heterogeneous vs. you i#ple#ent the ho#ogeneous.: ho#ogeneous.: -f -f interface, you start fro# i#ple#entors4subclasses i#ple#entors4subclasses are scratch without any ho#ogeneous, ho#ogeneous, tend towards an default i#ple#entation. abstract base class. -f they are ou have to obtain your heterogeneous, heterogeneous, use an tools fro# other classes; interface. (Now all - have to do nothing co#es with the is co#e up with a good interface other than a fewdefinition of constants. $his gives you hetero4ho#ogeneous hetero4ho#ogeneous in this freedo# to i#ple#ent a conte+t.) -f the various objects radically different internal are all of*a*'ind, and share a design. co##on state and behavior, then tend towards a co##on base class. -f all they share is a set of #ethod signatures, then tend towards an interface.
o#ogeneity
-f all the various i#ple#entations share is the #ethod signatures, then an interface wor's best.
&aintenance
-f your client code tal's 0ust li'e an interface, if your only in ter#s of an client code tal's only in ter#s of interface, you can easily an abstract class, you can easily change the concrete change the concrete i#ple#entation behind it, i#ple#entation behind it, using using a factory #ethod. a factory #ethod.
Speed
$erseness
Adding functionality
Summary
-f the various i#ple#entations are all of a 'ind and share a co##on status and behavior, usually an abstract class wor's best.
"low, re5uires e+tra indirection to find the corresponding corresponding #ethod in the actual class. &odern =ast 0<&s are discovering ways to reduce this speed penalty. ou can put shared code into an $he constant declarations abstract class, where you in an interface are all cannot into an interface. -f presu#ed public static interfaces want to share code, final, so you #ay leave you will have to write other that part out. ou can9t bubblegu# to arrange that. ou call any #ethods to #ay use #ethods to co#pute co#pute the initial values the initial values of your of your constants. ou constants and variables, both need not declare instance and static. ou #ust individual #ethods of an declare all the individual interface abstract. $hey #ethods of an abstract class are all presu#ed so. abstract. -f you add a new #ethod to an interface, you #ust trac' down all i#ple#entations of that interface in the universe and provide the# with a concrete i#ple#entation of that #ethod.
-f you add a new #ethod to an abstract class, you have the option of providing a default i#ple#entation of it. $hen all e+isting code will continue to wor' without change.
$he following article 'ic's off a three*part article series that will present definitions and sa#ples for different bject*riented Progra##ing concepts and its i#ple#entation in .N$. $he first part will e+a#ine the concepts of classes,objects, and structures.$he second part will e+a#ine the concepts of inheritance, abstraction, and poly#orphis#. $he third and last part will e+a#ine the concepts of interface, #ultiple interface inheritance, collections, and overloading. Introduction bject*riented Progra##ing (P) is a software develop#ent paradig# that suggests developers to split a progra# in building bloc's 'nown as objects. $he P paradig# allows developers to define the object9s data, functions, and its relationship with other objects. &icrosoft created the .N$ =ra#ewor' using P, and 'nowing this concepts has helped #e to understand the .N$ =ra#ewor' and to design and develop better software co#ponents. $he purpose of this article is to describe the basic P concepts using real world scenarios and to provide so#e code sa#ples that de#onstrate how to wor' with P and .N$. !lass $he #ost co##on definition states that a class is a te#plate for an object. "uppose that so#eone builds a paper pattern for a shirt. All the shirts done with the sa#e paper pattern will be identical (sa#e design, si>e, etc.). -n this sa#ple, the paper pattern is the class and the shirt is the object. $o build the sa#e e+act shirt over and over, you need the paper pattern as a te#plate. Another great e+a#ple are house plans and blueprints. $he plans and blueprints define the nu#ber of roo#s, the si>e of the 'itchen, the nu#ber of floors, and #ore. -n this real world sa#ple, the house plans and blueprints are the class and the house is the object. -n P you progra# a class as a te#plate for a specific object or groups ob objects that will always have the sa#e features. !lass members A class has different #e#bers, and developers in &icrosoft suggest to progra# the# in the following order •
• • • •
• • •
amespace $he na#espace is a 'eyword that defines a distinctive na#e or last na#e for the class. A na#espace categori>es and organi>es the library (asse#bly) where the class belongs and avoids collisions with classes that share the sa#e na#e. !lass declaration ?ine of code where the class na#e and type are defined. %ields "et of variables declared in a class bloc'. !onstants "et of constants declared in a class bloc'. !onstructors A #ethod or group of #ethods that contains code to initiali>e the class. (roperties $he set of descriptive data of an object. )vents Progra# responses that get fired after a user or application action. Methods "et of functions of the class.
•
&estructor A #ethod that is called when the class is destroyed. -n #anaged code, the @arbage 1ollector is in charge of destroying objects; however, in so#e cases developers need to ta'e e+tra actions when objects are being released, such as freeing handles or deallocating un#anaged objects. -n .N$, there is no concept of deter#inistic destructors. $he @arbage 1ollector will call the =inali>e() #ethod at a non*deter#inistic ti#e while reclai#ing #e#ory for the application.
Access keywords Access 'eywords define the access to class #e#bers fro# the sa#e class and fro# other classes. $he #ost co##on access 'eywords are • • •
• •
•
(ublic Allows access to the class #e#ber fro# any other class. (rivate Allows access to the class #e#ber only in the sa#e class. (rotected Allows access to the class #e#ber only within the sa#e class and fro# inherited classes. Internal Allows access to the class #e#ber only in the sa#e asse#bly. (rotected internal Allows access to the class #e#ber only within the sa#e class, fro# inherited classes, and other classes in the sa#e asse#bly. Static -ndicates that the #e#ber can be called without first instantiating the class.
$he following sa#ple code illustrates a sa#ple class in 12 444 12 444-#ported na#espaces using "yste#; 444 Na#espace 1onsider using 1o#panyNa#e.Product.1o#ponent$ype na#espace 7otNet$reats.".P1"harp % 4441lass declaration public class e#ployee % 444=ields private string na#e; private int salary; 4441onstants private const int anual3onus B CDDD; 4441onstructor public e#ployee() % 444Properties public string Na#e % get % return na#e; set %
na#e B value; public int "alary % get % return salary; set % salary B value; 444 vent handlers public event ventandler nPro#otion % add % re#ove % 444 ðods public void 7uplicate"alary() % salary B salaryEF; ?isting C. "a#ple class i#ple#entation in 12 $he following sa#ple code illustrates a sa#ple class in <3.N$ 9 <3.N$ 9-#ported na#espaces -#ports "yste# 9 Na#espace 1onsider using 1o#panyNa#e.Product.1o#ponent$ype Na#espace 7otNet$reats.".P<3N$ 91lass declaration Public 1lass e#ployee 9=ields Private na#e As "tring Private salary As -nteger 91onstants Private 1onst anual3onus As -nteger B CDDD 91onstructors Public "ub New() &y3ase.New() nd "ub 9Properties
Public Property Na#e() As "tring @et 6eturn na#e nd @et "et(3y
•
•
*b+ect identity &eans that every object is uni5ue and can be differentiated fro# other objects. ach ti#e and object is created (instantiated) the object identity is defined. *b+ect behavior 8hat the object can do. -n P, #ethods wor' as functions that define the set of actions that the object can do. *b+ect state $he data stored within the object at any given #o#ent. -n P, fields, constants, and properties define the state of an object.
Structures Not everything in the real world should be represented as a class. "tructures are suitable to represent lightweight objects. "tructures can have #ethods and properties and are useful for defining types that act as user*defined pri#itives, but
contain arbitrary co#posite fields. $he .N$ =ra#ewor' defines so#e structures such as "yste#.7rawing.6ectangle, "yste#.7rawing.Point, and "yste#.7rawing.1olor. $he following code sa#ple represents a structures in 12
444 12 struct Point % private int +; private int y; Point(int +, int y) % this.+ B +; this.y B y; public int G % get % return +; set % + B value; public int % get % return y; set % y B value; ?isting H. "a#ple structure i#ple#entation in 12 $he following code sa#ple represents a structure in <3.N$ 9 <3.N$ "tructure Point Private + As -nteger Private y As -nteger "ub New(3y
&e.y B y nd "ub Public Property G() As -nteger @et 6eturn + nd @et "et(3y
Summary $he following article is the second of a three*part article series that presents definitions and sa#ples for different bject*riented Progra##ing (P) concepts and its i#ple#entation in .N$. $he first part e+a#ined the concepts of classes, objects, and structures. $his part e+a#ines the concepts of inheritance, abstraction, and poly#orphis#. $he third and last part will e+a#ine the concepts of interface, #ultiple interface inheritance, collections, and overloading. Introduction -n Part C of bject*riented Progra##ing 1oncepts and .N$, - defined the concepts of class, object, and structure. -n addition to defining the concepts, - e+plained real world sa#ples and presented sa#ple code in 12 and <3.N$ to create classes and structs. $he first article also e+plains objects as independent building bloc's.
-n Part F of bject*riented Progra##ing 1oncepts and .N$, - will e+plain the concepts of inheritance, abstraction, and poly#orphis#. - will also present a Jnified &odel ?anguage (J&?) class diagra# to represent an object #odel that will help as a visual aid to e+plain so#e concepts. $he purpose of this article is to e+plain a series of relationships between objects. Inheritance -n the real world there are #any objects that can be speciali>ed. -n P, a parent class can inherit its behavior and state to children classes. $his concept was developed to #anage generali>ation and speciali>ation in P and is represented by a is*a relationship. $he following ter#s are co##only used na#es given to parent and child classes in P • • • •
"uperclass Parent class. "ubclass 1hild class. 3ase class Parent class. 7erived class 1hild class
$he #ost co##on real world sa#ple to e+plain inheritance is the geo#etric shapes object #odel. "5uares, circles, triangles, rectangles, pentagons, he+agons, and octagons are geo#etric shapes. $he following figure shows a sa#ple set of geo#etric figures
=igure C. @eo#etric shapes.
$he concept of generali>ation in P #eans that an object encapsulates co##on state an behavior for a category of objects. $he general object in this sa#ple is the geo#etric shape. &ost geo#etric shapes have area, peri#eter, and color. $he concept of speciali>ation in P #eans that an object can inherit the co##on state and behavior of a generic object; however, each object needs to define its own special and particular state an behavior. -n =igure C, each shape has its own color. ach shape has also particular for#ulas to calculate its area and peri#eter. -nheritance #a'es code elegant and less repetitive. -f we 'now that all shapes have color, should we progra# a color attribute for each shapeK $he answer is no! 8ould it be a better idea to create a shape class that has a color attribute and to #a'e all the speciali>ed shapes to inherit the color attributeK $he answer is yes! An object #odel for this sa#ple could have a shape parent class and a derived class for each specific shape. $he following J&? class diagra# shows the set of classes needed to #odel the geo#etric shapes sa#ple. bserve the field, properties, and #ethods for each class
=igure F. $he "hape class is the parent class. "5uare, 6ectangle, and 1ircle are derived classes that inherit fro# "hape. $he triangle*connector in the diagra# represents an is*a relationship. $he .N$ fra#ewor' has #any base classes. verything is derived fro# "yste#.bject. ou can create al#ost anything you i#agine using the built*in functionality provided in the .N$ =ra#ewor' 1lass ?ibrary. $o create a derived class in 12, the class declaration should be done as class child parent $o create a derived class in <3.N$, the class declaration should be done as
1lass child -nherits parent nd 1lass
Multiple inheritance &ultiple inheritance is the possibility that a child class can have #ultiple parents. u#an beings have always two parents, so a child will have characteristics fro# both parents. -n P, #ultiple inheritance #ight beco#e difficult to handle because it allows a#biguity for the co#piler. $here are progra##ing languages such as 1LL that allow #ultiple inheritance; however, other progra##ing languages such as 0ava and the .N$ =ra#ewor' languages do not allow #ultiple inheritance. &ultiple inheritance can be e#ulated in .N$ using &ultiple -nterface -nheritance, which - will e+plain in Part H of this series. Sealed class A sealed class is a class that does not allow inheritance. "o#e object #odel designs need to allow the creation of new instances but not inheritance, if this is the case, the class should be declared as sealed. $o create a sealed class in 12, the class declaration should be done as sealed class "hape $o create a sealed class in <3.N$, the class declaration should be done as Non-nheritable 1lass "hape Abstraction Abstraction is :the process of identifying co##on patterns that have syste#atic variations; an abstraction represents the co##on pattern and provides a #eans for specifying which variation to use: (6ichard @abriel). An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or #ore abstract #ethods that do not have i#ple#entation. Abstract classes allow speciali>ation of inherited classes. =igure F shows a "hape class, which is an abstract class. -n the real world, you never calculate the area or peri#eter of a generic shape, you #ust 'now what 'ind of geo#etric shape you have because each shape (eg. s5uare, circle, rectangle, etc.) has its own area and peri#eter for#ulas. $he parent class shape forces all derived classes to define the behavior for 1alculateArea() and 1alculatePeri#eter(). Another great e+a#ple is a ban' account. People own savings accounts, chec'ing accounts, credit accounts, invest#ent accounts, but not generic ban' accounts. -n this case, a ban' account can be an abstract class and all the other speciali>ed ban' accounts inherit fro# ban' account.
$o create an abstract class in 12, the class declaration should be done as abstract class "hape $o create an abstract class in <3.N$, the class declaration should be done as &ust-nherit 1lass "hape $o following code shows a sa#ple i#ple#entation of an abstract class 444 12 using "yste#; na#espace 7otNet$reats.".P"a#ples % public abstract class "hape % private float area; private "yste#.7rawing.1olor color; private float peri#eter; public float Area % get % return area; set % area B value; public "yste#.7rawing.1olor 1olor % get % return color; set % color B value; public float Peri#eter % get % return peri#eter; set % peri#eter B value;
public abstract void 1alculateArea(); public abstract void 1alculatePeri#eter(); ?isting C. $he "hape abstract class in 12. (olymorphism Poly#orphis# allows objects to be represented in #ultiple for#s. ven though classes are derived or inherited fro# the sa#e parent class, each derived class will have its own behavior. Poly#orphis# is a concept lin'ed to inheritance and assures that derived classes have the sa#e functions even though each derived class perfor#s different operations. =igure F shows a 6ectangle, a 1ircle, and "5uare. All of the# are shapes and as shapes their area and peri#eter can be calculated; however, each shape calculates its area in a speciali>ed way. 7eclaring a #e#ber as abstract allows poly#orphis#. $he "hape class defines the 1alculateArea() and 1alculatePeri#eter() #ethods as abstract, this allows each derived class to override the i#ple#entation of the parent9s #ethods. $o following sa#ple code shows an i#ple#entation of a derived class (rectangle). $he specific 1alculateArea() and 1alculatePeri#eter() #ethods for the rectangle class illustrate poly#orphis# 444 12 using "yste#; na#espace 7otNet$reats.".P"a#ples % class 6ectangle "hape % private float height; private float width; public rectangle(float height, float width) % height B height; width B width; public float eight % get % return height; set % height B value; public float 8idth %
get % return width; set % width B value; public override void 1alculateArea() % this.Area B height E width; public override void 1alculatePeri#eter() % this.Peri#eter B (height E F) L (width E F); ?isting F. Poly#orphis# represented in the 6ectangle9s #ethods. ,irtual keyword $he virtual 'eyword allows poly#orphis# too. A virtual property or #ethod has an i#ple#entation in the base class, and can be overriden in the derived classes. $o create a virtual #e#ber in 12, use the virtual 'eyword public virtual void 7raw() $o create a virtual #e#ber in <3.N$, use the verridable 'eyword Public verridable =unction 7raw() *verride keyword verriding is the action of #odifying or replacing the i#ple#entation of the parent class with a new one. Parent classes with virtual or abstract #e#bers allow derived classes to override the#. $o override a #e#ber in 12, use the override 'eyword public override void 1alculateArea() $o override a #e#ber in <3.N$, use the verrides 'eyword Public verrides =unction 1alculateArea() !onclusion
-nheritance allows developers to #anage a generali>ation and speciali>ation relationship between objects. P concepts such as abstraction and poly#orphis# help to define better object #odels where object hierarchies are designed with reusability in #ind. -n this article, - e+a#ined the concept of inheritance, abstraction, and poly#orphis#. $he third and last part of this series will e+a#ine the concepts of interface, #ultiple interface inheritance, collections, and overloading. ote $he sa#ple source codeE for this article wor's only in
9# !ntroduction I ha%e noticed an increase in the number of articles published in the Architect category in code-project during the last few months. 8he number of readers for most of these articles is also high" though the ratings for the articles are not. 8his indicates that readers are interested in reading articles on Architecture" but the Puality does not match their e&pectations. 8his article is a constructi%e attempt to group7 define7 e&plain all introductory concepts of software architecture for well seasoned de%elopers who are looking to take their ne&t step as system architects. @ne day I read an article that said that the richest percent own half the worldFs wealth. It also said that the richest , percent of adults owned <6 percent of global assets in the year 666. And further" that the richest ,6 percent of adults accounted for OL percent of the worldFs total wealth. o there is an unbalanced distribution of wealth in the physical world. $a%e you e%er thought of an unbalanced distribution of knowledge in the software worldQ According to my %iew point" the massi%e e&pansion of the software industry is forcing de%elopers to use already implemented libraries" ser%ices and frameworks to de%elop software within e%er shorter periods of time. 8he new de% elopers are trained to use (I would say more often) already de%eloped software components" to complete the de%elopment Puicker. 8hey just plug in an e&isting library and some how manage to achie%e the rePuirements. Kut the sad part of the story is" that they ne%er get a training to define" design the architecture for" and implement such components. As the number of years pass by" these de%elopers become leads and also software architects. 8heir titles change" but the old legacy of not understanding" of not ha%ing any architectural e&perience continues" creating a %acuum of good architects. 8he bottom line is that only a small percentage of de%elopers know how to design a truly object oriented system. 8he solution to this problem is getting harder e%ery day as the aggressi%e nature of the software industry does not support an easy adjustment to e&isting processes" and also the related online teaching materials are either comple& or less practical or sometimes e%en wrong. 8he most of them use impractical" irrele%ant e&les of shap es" animals and many other physical world entities to teach concepts of software architecture. 8here are only %ery few good business-oriented design references. Mnfortunately" I myself am no
e&ception and am a result of this %ery same system. I got the same education that all of you did" and also referred to the same resource set you all read. Coming back to the initial point" I noticed that there is a knowledge gap" increasing e%ery day" between the architects who know how to architect a system properly and the others who do not know. 8he ones" who know" know it right. Kut the ones" who d o not know" know nothing. Hust like the world’s wealth distribution" it is an unbalanced distribution of knowledge.
7# .ackground 8his article began after reading and hearing the Puestions new de%elopers ha%e" on basics of software architecture. 8here are some good articles out there" but still de%elopers struggle to understand the basic concepts" and more importantly" the way to apply them correctly. As I see it" newcomers will always struggle to understand a precise definition of a new concept" because it is always a new and hence unfamiliar idea. 8he one" who has e&perience" understands the meaning" but the one who doesn’t" struggles to understand the %ery same definition. It is like that. +mployers want e&perienced employees. o they say" you need to ha%e e&perience to get a job. Kut how the hell is one supposed to ha%e that e&perience if no one is willing to gi%e him a jobQ As in the general case" the start with software architecture is no e&ception. It will be difficult. 'hen you start to design your %ery first system" you will try to apply e%erything you know or learned from e%erywhere. Bou will feel that an interface needs to be defined for e%e ry class" like I did once. Bou will find it harder to understand when and when not to do something. Hust prepare to go through a painful process. @thers will critici*e you" may laugh at you and say that the way you ha%e designed it is wrong. ?isten to them" and learn continuously. In this process you will also ha%e to read and think a lot. I hope that this article will gi%e you the right start for that long journey. “The knowledge of the actions of great men, acquired by long exerience in contemorary affairs, and a continual study of antiquity” N I read this phrase when I was reading the book named “The !rt of "ar ”" seems applicable here" isn’t itQ
:# Prere;uisites 8his article is an effort to pro%ide an accurate information pool for new de%elopers on the basics of software architecture" focusing on O bject Oriented Programming (##$ ). If you are a de%eloper" who has a minimum of three or more years of continuous de%elopment e&perience and has that hunger to learn more" to step-in to the ne&t le%el to become a software architect" this article is for you.
<# ,he 'ain Content
<#9# What is Software 3rchitecture? oftware Architecture is defined to be the rules" heuristics and patterns go%erning artitioning the problem and the system to be built into discrete pieces 8echniPues used to create interfaces between these pieces 8echniPues used to manage o%erall structure and flow 8echniPues used to interface the system to its en%ironment Appropriate use of de%elopment and deli%ery approaches" techniPues and tools. • • • • •
<#7# Why 3rchitecture is i(portant?
8he primary goal of software architecture is to define the non-functional rePuirements of a system and define the en%ironment. 8he detailed design is followed by a de finition of how to deli%er the functional beha%ior within the architectural rules. Architecture is important because it Controls comple&ity +nforces best practices Gi%es consistency and uniformity Increases predictability +nables re-use. • • • • •
<#:# What is OOP? ##$ is a design philosophy. It stands for @bject @riented rogramming. O bject-Oriented Programming (##$ ) uses a different set of programming languages than old procedural programming languages (C, $ascal " etc.). +%erything in ##$ is grouped as self sustainable Rob%ectsR. $ence" you gain re-usability by means of four main object-oriented programming concepts. In order to clearly understand the object orientation" let’s take your “hand ” as an e&le. 8he “hand ” is a class. Bour body has two objects of type hand" named left hand
and right hand. 8heir main functions are controlled7 managed by a set of electrical signals sent through your shoulders (through an interface). o the shoulder is an interface which your body uses to interact with your hands. 8he hand is a well architected class. 8he hand is being re-used to create the left hand and the right hand by slightly changing the properties of it.
<#<# What is an Object? An object can be considered a Rthing R that can perform a set of related acti%ities. 8he set of acti%ities that the object performs defines the objectFs beha%ior. or e&le" the hand can grip something or a Student (ob%ect ) can gi%e the name or address. In pure ##$ terms an object is an instance of a class.
<#=# What is a Class?
A class is simply a representation of a type of ob%ect . It is the blueprint7 plan7 template that describe the details of an ob%ect . A class is the blueprint from which the indi%idual objects are created. Class is composed of three things a name" attributes" and operations. Collapse S Copy Code public class Student { }
According to the sample gi%en below we can say that the student object" named ob%ectStudent " has created out of the Student class. Collapse S Copy Code Student objectStudent = new Student();
In real world" youFll often find many indi%idual objects all of the same kind. As an e&le" there may be thousands of other bicycles in e&istence" all of the same make and model. +ach bicycle has built from the same blueprint. In object-oriented terms" we say that the bicycle is an instance of the class of objects known as bicycles. In the software world" though you may not ha%e reali*ed it" you ha%e already used classes. or e&le" the Text&ox control" you always used" is made out of the Text&ox class" which defines its appearance and capabilities. +ach time you drag a Text&ox control" you are actually creating a new instance of the Text&ox class.
<#># *ow to identify and design a Class?
8his is an art/ each designer uses different techniPues to identify classes. $owe%er according to @bject @riented ;esign rinciples" there are fi%e principles that you must follow when design a class" •
•
•
•
•
# - 8he ingle #esponsibility rinciple A class should ha%e one" and only one" reason to change. @C - 8he @pen Closed rinciple Bou should be able to e&tend a classes beha%ior" without modifying it. ? - 8he ?isko% ubstitution rinciple;eri%ed classes must be substitutable for their base classes. ;I - 8he ;ependency In%ersion rinciple;epend on abstractions" not on concretions. I - 8he Interface egregation rinciple0ake fine grained interfaces that are client specific.
or more information on design principles" please refer to @bject 0entor . Additionally to identify a class correctly" you need to identify the full list of leaf le%el functions7 operations of the system (granular le%el use cases of the system). 8hen you can proceed to group each function to form classes (classes will group same types of functions7 operations). $owe%er a well defined class must be a meaningful grouping of a set of functions and should support the re-usability while increasing e&pandability7 maintainability of the o%erall system. In software world the concept of di%iding and conPuering is always recommended" if you start analy*ing a full system at the start" you will find it harder to manage. o the better approach is to identify the module of the system first and then dig deep in to each module separately to seek out classes. A software system may consist of many classes. Kut in any case" when you ha%e many" it needs to be managed. 8hink of a big organi*ation" with its work force e&ceeding se%eral thousand employees (let’s take one employee as a one class). In order to manage such a work force" you need to ha%e proper management policies in place. ame techniPue can be applies to manage classes of your software system as well. In order to manage the classes of a software system" and to reduce the comple&ity" the system designers use se%eral techniPues" which can be grouped under four main concepts named +ncapsulation" Abstraction" Inheritance" and $olymorhism. 8hese concepts are the four main gods of ##$ world and in software term" they are called four main @bject @riented rogramming (##$ ) Concepts.
<#6# What is Encapsulation %or infor(ation hiding&? 8he encapsulation is the inclusion within a program object of all the resources need for the object to function - basically" the methods and the data. In ##$ the encapsulation is mainly achie%ed by creating classes" the classes e&pose public methods and properties. 8he class is kind of a container or capsule or a cell" which encapsulate the set of methods"
attribute and properties to pro%ide its indented functionalities to other classes. In that sense" encapsulation also allows a class to chang e its internal implementation without hurting the o%erall functioning of the system. 8hat idea of encapsulation is to hide how a class does it but to allow rePuesting what to do.
In order to modulari*e7 define the functionality of a one class" that class can uses functions7 properties e&posed by another class in many different ways. According to @bject @riented rogramming there are se%eral techniPues" classes can use to link with each other and they are named association" aggregation" and composition. 8here are se%eral other ways that an encapsulation can be used" as an e&le we can take the usage of an interface. 8he interface can be used to hide the information of an implemented class. Collapse S Copy Code IStudent myStudent = new ocalStudent(); IStudent myStudent = new !oreignStudent();
According to the sample abo%e (let’s assume that 'ocalStudent and oreignStudent are implemented by the Student interface) we can see how 'ocalStudent and oreignStudent are hiding their" locali*e implementing information through the Student interface.
<## What is 3ssociation? Association is a (TaT) relationship between two classes. It allows one object instance to cause another to perform an action on its behalf. Association is the more general term that define the relationship between two classes" where as the aggregation and composition are relati%ely special. Collapse S Copy Code public class Student"egistrar { public Student"egistrar (); { new "ecord#anager()$Initiali%e(); } }
In this case we can say that there is an association between Student*egistrar and *ecord+anager or there is a directional association from Student*egistrar to *ecord+anager or tudent#egistrar use a (T0seT) *ecord+anager . ince a direction is e&plicitly specified" in this case the controller class is the Student*egistrar .
8o some beginners" association is a confusing concept. 8he troubles created not only by the association alone" but with two other ##$ concepts" that is association" aggregation and composition. +%ery one understands association" before aggregation and composition are described. 8he aggregation or composition cann ot be separately understood. If you understand the aggregation alone it will crack the definition gi%en for association" and if you try to understand the composition alone it will always threaten the definition gi%en for aggregation" all three concepts are closely related" hence must study together" by comparing one definition to another. ?et’s e&plore all three and see whether we can understand the differences between these useful concepts.
<#@# What is the difference between 3ssociation5 3ggregation and Co(position? Association is a (TaT) relationship between two classes" where one class use another. Kut aggregation describes a special type of an association. Aggregation is the (TtheT) relationship between two classes. 'hen object of one class h as an (ThasT) object of another" if second is a part of first (containment relationship) then we called that there is an aggregation between two classes. Mnlike association" aggregation always insists a direction. Collapse S Copy Code public class &niversity { private C'ancellor universityC'ancellor = new C'ancellor(); }
In this case I can say that ni-ersity aggregate Chancellor or ni-ersity has an (Thas1aT) Chancellor . Kut e%en without a Chancellor a ni-ersity can e&ists. Kut the aculties cannot e&ist without the ni-ersity" the life time of a aculty (or aculties) attached with the life time of the ni-ersity . If ni-ersity is disposed the aculties will not e&ist. In that case we called that ni-ersity is composed of aculties. o that composition can be recogni*ed as a special type of an aggregation.
ame way" as another e&le" you can say that" there is a composite relationship in between a ey/alue$airCollection and a ey/alue$air . 8he two mutually depend on each other. .9et and Ha%a uses the Composite relation to define their Collections. I ha%e seen Composition is being used in many other ways too. $owe%er the more important factor" that most people forget is the life time factor. 8he life time of the two classes that has bond with a composite relation mutually depend on each other. If you take the .net Collection to understand this" there you ha%e the Collection +lement define inside (it is an inner part" hence called it is composed of) the Collection" farcing the +lement to get disposed with the Collection. If not" as an e&le" if you define the Collection and it’s +lement to be independent" then the relationship would be more of a type Aggregation" than a Composition. o the point is" if you want to bind two classes with Composite relation" more accurate way is to ha%e a one define inside the other class (making it a protected or pri%ate class). 8his way you are allowing the outer class to fulfill its purpose" while tying the lifetime of the inner class with the outer class. o in summary" we can say that aggregation is a special kind of an association and composition is a special kind of an aggregation. ( !ssociation01!ggregation0 1Comosition)
<#98# What is 3bstraction and )enerali"ation? Abstraction is an emphasis on the idea" Pualities and properties rather than the particulars (a suppression of detail). 8he importance of abstraction is deri%ed from its ability to hide irrele%ant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather
than how it is represented or how it works. 8hus" it is the primary means of managing comple&ity in large programs. 'hile abstraction reduces comple&ity by hiding irrele%ant detail" g enerali*ation reduces comple&ity by replacing multiple entities which perform similar functions with a single construct. Generali*ation is the broadening of app lication to encompass a larger domain of objects of the same or different type. rogramming languages pro%ide generali*ation through %ariables" parameteri*ation" generics and olymorhism. It places the emphasis on the similarities between objects. 8hus" it helps to manage co mple&ity by collecting indi%iduals into groups and pro%iding a representati%e which can be used to specify any indi%idual of the group. Abstraction and generali*ation are often used together. Abstracts are generali*ed through parameteri*ation to pro%ide greater utility. In parameteri*ation" one or more parts of an entity are replaced with a name which is new to the entity. 8he name is used as a parameter. 'hen the parameteri*ed abstract is in%oked" it is in%oked with a binding of the parameter to an argument.
<#99# What is an 3bstract class? Abstract classes" which declared with the abstract keyword" cannot be instantiated. It can only be used as a super-class for other classes that e&tend the abstract class. Abstract class is the concept and implementation gets completed when it is being reali*ed by a subclass. In addition to this a class can inherit only from one abstract class (but a class may implement many interfaces) and must o%erride all its abstract methods7 properties and may o%erride %irtual methods7 properties. Abstract classes are ideal when implementing frameworks. As an e&le" let’s study the abstract class named 'ogger&ase below. lease carefully read the comments as it will help you to understand the reasoning behind this code. Collapse S Copy Code public abstract class oggerase { *summary+ ,ield is private- so it intend to use inside t'e class only *summary+ private log.net$Iog logger = null;
*summary+ protected- so it only visible ,or in'erited class *summary+ protected oggerase() { /'e private object is created inside t'e constructor logger = log.net$og#anager$0etogger(t'is$og1re,i2); /'e additional initiali%ation is done immediately a,ter log.net$Con,ig$34#Con,igurator$Con,igure(); }
*summary+ 5'en you de,ine t'e property as abstract it ,orces t'e in'erited class to override t'e og1re,i2 So- wit' t'e 'elp o, t'is tec'ni6ue t'e log can be made inside t'e abstract class itsel,- irrespective o, it origin$ I, you study care,ully you will ,ind a reason ,or not to 'ave 7set8 met'od 'ere$ *summary+ protected abstract System$/ype og1re,i2 { get; }
*summary+ Simple log met'od w'ic' is only visible ,or in'erited classes *summary+ *param name=9message9+*param+ protected void og:rror(string message) { i, (t'is$logger$Is:rror:nabled) { t'is$logger$:rror(message); } } *summary+ 1ublic properties w'ic' e2poses to in'erited class and all ot'er classes t'at 'ave access to in'erited class *summary+ public bool Is/'isog:rror { get { return t'is$logger$Is:rror:nabled; } }
}
8he idea of ha%ing this class as an abstract is to define a framework for e& ception logging. 8his class will allow all subclass to gain access to a common e&ception logging module and will facilitate to easily replace the logging library. Ky the time you define the 'ogger&ase" you wouldn’t ha%e an idea about other modules of the system. Kut you do ha%e a concept in mind and that is" if a class is going to log an e&ception" they ha%e to inherit the 'ogger&ase. In other word the 'ogger&ase pro%ide a framework for e&ception logging. ?et’s try to understand each line of the abo%e code. ?ike any other class" an abstract class can contain fields" hence I used a pri%ate field named logger declare the 'og interface of the famous log
8he access modifier of the constructor of the 'ogger&ase is protected. 8he public constructor has no use when the class is of type abstract. 8he abstract classes are not allowed to instantiate the class. o I went for the protected constructor. 8he abstract property named ?ogrefi& is an important one. It enforces and guarantees to ha%e a %alue for 'og$refix ( 'og$refix uses to obtain the detail of the source class" which the e&ception has occurred) for e%ery subclass" before they in%oke a method to log an error. 8he method named 'og2rror is protected" hence e&posed to all subclasses. Bou are not allowed or rather you cannot make it public" as any class" without inheriting the 'ogger&ase cannot use it meaningfully. ?et’s find out why the property named sThis'og2rror is public. It may be important7 useful for other associated classes of an inherited class to know whether the associated member logs its errors or not. Apart from these you can also ha%e %irtual methods defined in an abstract class. 8he %irtual method may ha%e its default implementation" where a subclass can o%erride it when rePuired. All and all" the important factor here is that all ##$ concepts should be used carefully with reasons" you should be able to logically e&plain" why you make a property a public or a field a pri%ate or a class an abstract. Additionally" when architecting frameworks" the ##$ concepts can be used to forcefully guide the system to be de%eloped in the way framework architect’s wanted it to be architected initially.
<#97# What is an !nterface? In summary the Interface separates the implementation and defines the structure" and this concept is %ery useful in cases where you need the implementation to be interchangeable. Apart from that an interface is %ery useful when the implementation changes frePuently. ome say you should define all classes in terms of interfaces" but I think recommendation seems a bit e&treme. Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can co ntain properties (which are also implicitly public and abstract). Interface definition begins with the keyword interface. An interface like that of an abstract class cannot be instantiated. If a class that implements an interface does not define all the methods of the interface" then it must be declared abstract and the method definitions must be pro%ided by the subclass that e&tends the abstract class. In addition to this an interfaces can inherit other interfaces.
8he sample below will pro%ide an interface for our 'ogger&ase abstract class. Collapse S Copy Code public inter,ace Iogger { bool Is/'isog:rror { get; } }
<#9:# What is the difference between a Class and an !nterface? In .9et7 C: a class can be defined to implement an interface and also it supports multiple implementations. 'hen a class implements an interface" an ob%ect of such class can be encapsulated inside an interface. If +y'ogger is a class" which implements 'ogger, there we can write Collapse S Copy Code Iogger log = new #yogger();
A class and an interface are two different types (conceptually). 8heoretically a class emphasis the idea of encapsulation" while an interface emphasis the idea of abstraction (by suppressing the details of the implementation). 8he two poses a clear separation from one to another. 8herefore it is %ery difficult or rather impossible to ha%e an effecti%e meaningful comparison between the two" but it is %ery useful and also meaningful to ha%e a comparison between an interface and an abstract class.
<#9<# What is the difference between an !nterface and an 3bstract class? 8here are Puite a big difference between an interface and an abstract class" e%en though both look similar. o o o o o o o
Interface definition begins with a keyword interface so it is of type interface Abstract classes are declared with the abstract keyword so it is of type class Interface has no implementation" but they ha%e to be implemented. Abstract class’s methods can ha%e implementations and they ha%e to be e&tended. Interfaces can only ha%e method declaration (implicitly public and abstract) and fields (implicitly public static) Abstract class’s methods can’t ha%e implementation only when declared abstract. Interface can inherit more than one interfaces
o o o o o o o o
Abstract class can implement more than one interfaces" but can inherit only one class Abstract class must o%erride all abstract method and may o%erride % irtual methods Interface can be used when the implementation is changing Abstract class can be used to pro%ide some default beha%ior for a base class. Interface makes implementation interchangeable Interface increase security by hiding the implementation Abstract class can be used when implementing framework Abstract classes are an e&cellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.
Abstract classes let you define some beha%iors/ they force your subclasses to pro%ide others. or e&le" if you ha%e an application framework" an abstract class can be used to pro%ide the default implementation of the ser%ices and all mandatory modules such as e%ent logging and message handling etc. 8his approach allows the de%elopers to de%elop the application within the guided help pro%ided by the framework. $owe%er" in practice when you come across with some application-specific functionality that only your application can perform" such as startup and shutdown tasks etc. 8he abstract base class can declare %irtual shutdown and startup methods. 8he base class knows that it needs those methods" but an abstract class lets your class admit that it doesnFt know how to perform those actions/ it only knows that it must initiate the actions. 'hen it is time to start up" the abstract class can call the startup method. 'hen the base class calls this method" it can e&ecute the method defined by the child class.
<#9=# What is !(plicit and E/plicit !nterface !(ple(entations? As mentioned before .9et support multiple implementations" the conc ept of implicit and e&plicit implementation pro%ide safe way to implement methods of multiple interfaces by hiding" e&posing or preser%ing identities of each of interface methods" e%en when the method signatures are the same. ?etFs consider the interfaces defined below. Collapse S Copy Code inter,ace I3isposable { void 3ispose(); }
$ere you can see that the class Student has implicitly and e&plicitly implemented the method named 3isose() %ia 3isose and 3isosable.3isose.
Collapse S Copy Code class Student I3isposable { public void 3ispose() { Console$5riteine(9Student$3ispose9); }
void I3isposable$3ispose() { Console$5riteine(9I3isposable$3ispose9); }
}
<#9># What is !nheritance? Ability of a new class to be created" from an e&isting class by e&tending it" is called inheritance.
Collapse S Copy Code public class :2ception { } public class I4:2ception :2ception { }
According to the abo%e e&le the new class ( #2xcetion)" which is called the deri%ed class or subclass" inherits the members of an e&isting class ( 2xcetion)" which is called the base class or super-class. 8he class #2xcetion can e&tend the functionality of the class +&ception by adding new types and methods and by o%erriding e&isting ones. Hust like abstraction is closely related with generali*ation" the inheritance is closely related with speciali*ation. It is important to discuss those two concepts together with generali*ation to better understand and to reduce the comple&ity.
@ne of the most important relationships among objects in the real world is speciali*ation" which can be described as the “is1a” relationship. 'hen we say that a dog is a mammal" we mean that the dog is a speciali*ed kind of mammal. It has all the characteristics of any mammal (it bears li%e young" nurses with milk" has h air)" but it speciali*es these characteristics to the familiar characteristics of canis domesticus. A cat is also a mammal. As such" we e&pect it to share certain characteristics with the dog that are gene rali*ed in 0ammal" but to differ in those characteristics that are speciali*ed in cats. 8he speciali*ation and generali*ation relationships are both reciprocal and hierarchical. peciali*ation is just the other side of the g enerali*ation coin 0ammal generali*es what is common between dogs and cats" and dogs and cats speciali*e mammals to their own specific subtypes. imilarly" as an e&le you can say that both #2xcetion and Security2xcetion are of type +&ception. 8hey ha%e all characteristics and beha%iors of an +&ception" 8hat mean the #2xcetion is a speciali*ed kind of +&ception. A Security2xcetion is also an 2xcetion. As such" we e&pect it to share certain characteristic with #2xcetion that are generali*ed in +&ception" but to differ in those characteristics that are speciali*ed in Security2xcetions. In other words" +&ception generali*es the shared characteristics of both #2xcetion and Security2xcetion" while #2xcetion and Security2xcetion speciali*e with their characteristics and beha%iors. In ##$ " the speciali*ation relationship is implemented using the principle called inheritance. 8his is the most common and most natural and widely accepted way of implement this relationship.
<#96# What is Poly(orphis(s? olymorphisms is a generic term that means Fmany shapesF. 0o re precisely $olymorhisms means the ability to rePuest that the same operations be performed by a wide range of different types of things. At times" I used to think that understanding @bject @riented rogramming concepts ha%e made it difficult since they ha%e grouped under four main concepts" while each concept is closely related with one another. $ence one has to be e&tremely careful to correctly understand each concept separately" while understanding the way each related with other concepts. In ##$ the olymorhisms is achie%ed by using many different techniPues named method o%erloading" operator o%erloading and method o%erriding"
<#9# What is 'ethod O4erloading? 8he method o%erloading is the ability to define se%eral methods all with the same na me. Collapse S Copy Code public class #yogger
{ public void og:rror(:2ception e) { Implementation goes 'ere } public bool og:rror(:2ception e- string message) { Implementation goes 'ere } }
<#9@# What is Operator O4erloading? 8he operator o%erloading (less commonly known as ad-hoc olymorhisms) is a specific case of olymorhisms in which some or all of operators like >" - or 11 are treated as polymorphic functions and as such ha%e different beha%iors depending on the types of its arguments. Collapse S Copy Code public class Comple2 { private int real; public int "eal { get { return real; } } private int imaginary; public int Imaginary { get { return imaginary; } } public Comple2(int real- int imaginary) { t'is$real = real; t'is$imaginary = imaginary; } public static Comple2 operator <(Comple2 c- Comple2 c>) { return new Comple2(c$"eal < c>$"eal- c$Imaginary < c>$Imaginary); } }
I abo%e e&le I ha%e o%erloaded the plus operator for adding two comple& numbers. 8here the two properties named #eal and Imaginary has been declared e&posing only the rePuired “ get ” method" while the object’s constructor is demanding for mandatory real and imaginary %alues with the user defined constructor of the class.
<#78# What is 'ethod O4erriding? 0ethod o%erriding is a language feature that allows a subclass to o%erride a specific implementation of a method that is already pro%ided by one of its super-classes.
A subclass can gi%e its own definition of methods but need to ha%e the same signature as the method in its super-class. 8his means that when o%erriding a method the subclassFs method has to ha%e the same name and parameter list as the super-classFs o%erridden method. Collapse S Copy Code using System; public class Comple2 { private int real; public int "eal { get { return real; } } private int imaginary; public int Imaginary { get { return imaginary; } } public Comple2(int real- int imaginary) { t'is$real = real; t'is$imaginary = imaginary; } public static Comple2 operator <(Comple2 c- Comple2 c>) { return new Comple2(c$"eal < c>$"eal- c$Imaginary < c>$Imaginary); } public override string /oString() { return (String$!ormat(9{?} < {}i9- real- imaginary)); } }
In abo%e e&le I ha%e e&tended the implementation of the sample Comple& class gi%en under operator o%erloading section. 8his class has one o%erridden method named 4ToString5" which o%erride the default implementation of the standard 4ToString5 method to support the correct string con%ersion of a comple& number. Collapse S Copy Code Comple2 num = new Comple2(@- A); Comple2 num> = new Comple2(B- ); Ddd two Comple2 numbers using t'e overloaded plus operator Comple2 sum = num < num>; 1rint t'e numbers and t'e sum using t'e overriden /oString met'od Console$5riteine(9({?}) < ({}) = {>}9- num- num>- sum); Console$"eadine();
<#79# What is a 0se case?
A use case is a thing an actor percei%es from the system. A use case maps actors with functions. Importantly" the actors need not be people. As an e&le a system can perform the role of an actor" when it communicate with another system.
In another angle a use case encodes a typical user interaction with the system. In particular" it Captures some user-%isible function. •
•
Achie%es some concrete goal for the user.
A complete set of use cases largely defines the rePuirements for your system e%erything the user can see" and would like to do. 8he below diagram contains a set of use cases that describes a simple login module of a gaming website.
<#77# What is a Class Diagra(? A class diagrams are widely used to describe the types of objects in a system and their relationships. Class diagrams model class structure and contents using design elements such as classes" packages and objects. Class diagrams describe three different perspecti%es when designing a system" conceptual" specification" and implementation. 8hese perspecti%es become e%ident as the diagram is created and help solidify the design. 8he Class diagrams" physical data models" along with the system o%er%iew diagram are in my opinion the most important diagrams that suite the current day rapid application de%elopment rePuirements.
M0? 9otations
<#7:# What is a Package Diagra(? ackage diagrams are used to reflect the organi*ation of packages and their elements. 'hen used to represent class elements" package diagrams pro%ide a %isuali*ation of the name-spaces. In my designs" I use the package diagrams to organi*e classes in to different modules of the system.
<#7<# What is a Se;uence Diagra(? A sePuence diagrams model the flow of logic within a system in a %isual manner" it enable both to document and %alidate your logic" and are used for both analysis and design purposes. ePuence diagrams are the most popular M0? artifact for dynamic modeling" which focuses on identifying the beha%ior within your system.
<#7=# What is two1tier architecture? 8he two-tier architecture is refers to client7 ser%er architectures as well" the term client7 ser%er was first used in the ,UO6s in reference to personal computers (Cs) on a network. 8he actual client7 ser%er model started gaining acce ptance in the late ,UO6s" and later it was adapted to 'orld 'ide 'eb programming. According to the modern days use of two-tier architecture the user interfaces (or with A.9+8" all web pages) runs on the client and the database is stored on the ser%er. 8he actual application logic can run on either the client or the ser%er. o in this case the user interfaces are directly access the database. 8hose can also be non-interface processing engines" which pro%ide solutions to other remote7 local systems. In either case" today the two-tier model is not as reputed as the three-tier model. 8he ad%antage of the two-tier design is its simplicity" but the simplicity comes with the cost of scalability. 8he newer three-tier architecture" which is more famous" introduces a middle tier for the application logic.
<#7># What is three1tier architecture? 8he three tier software architecture (also known as three layer architectures) emerged in the ,UU6s to o%ercome the limitations of the two tier architecture. 8his architecture has aggressi%ely customi*ed and adopted by modern day system designer to web systems. 8hree-tier is a client-ser%er architecture in which the user interface" functional process logic" data storage and data access are de%eloped and maintained as independent modules" some time on separate platforms. 8he term Rthree0tier R or Rthree0layer R" as well as the concept of multi-tier architectures (often refers to as three-tier architecture)" seems to ha%e originated within #ational oftware.
8he =-8ier architecture has the following three tiers. ,. Presentation ,ier or Web Ser4er Mser Interface" displaying7 accepting data7 input to7 from the user . 3pplication Aogic .usiness Aogic ,ransaction ,ier or 3pplication Ser4er ;ata %alidation" acceptability check before being added to the database and all other business7 application specific operations =. Data ,ier or Database ser4er imple reading and writing method to database or any other storage" connection" command" stored procedures etc
<#76# What is '+C architecture?
8he 'odel-+iew-Controller ( +/C ) architecture separates the modeling of the domain" the presentation" and the actions based on user input into three separate classes. Mnfortunately" the popularity of this pattern has resulted in a number of faulty usages/ each technology ( 6a-a" !S$.72T etc) has defined it in their own way making it difficult to understand. In particular" the term RcontrollerR has been used to mean different things in different conte&ts. 8he definitions gi%en bellow are the closes possible ones I found for A.9+8 %ersion of +/C .
,. 'odel 3ataSet and typed 3ataSet (some times business object" object collection" J0? etc) are the most common use of the model. . +iew 8he !S$8 and !SC8 files generally handle the responsibilities of the %iew. =. Controllers 8he handling of e%ents or the controlling is usually done in the code behind class. In a comple& n-tier distributed system the +/C architecture place the %ital role of organi*ing the presentation tier of the system.
<#7# What is SO3? A ser%ice-oriented architecture is essentially a collection of ser%ices. 8hese ser%ices communicate with each other. 8he communication can in%ol%e either simple data passing or it could in%ol%e two or more ser%ices coordinating some acti%ity. ome means of connecting ser%ices to each other is needed. 8he .9et technology introduces the @A by mean of web ser%ices.
8he @A can be used as the concept to connect multiple systems to pro%ide ser%ices. It has itFs great share in the future of the I8 world. According to the imaginary diagram abo%e" we can see how the er%ice @riented Architecture is being used to pro%ide a set of centrali*ed ser%ices to the citi*ens of a country. 8he citi*ens are gi%en a uniPue identifying card" where that card carries all personal information of each citi*en. +ach ser%ice centers such as shopping comple&" hospital" station" and factory are ePuipped with a computer system where that system is connected to a central ser%er" which is responsible of pro%iding ser%ice to a city. As an e&le when a customer enter the shopping comple& the regional computer system report it to the central ser%er and obtain information about the customer before pro%iding access to the premises. 8he system welcomes the customer. 8he customer finished the shopping and then by the time he lea%es the shopping comple&" he will be asked to go through a billing process" where the regional computer system will manage the process. 8he payment will be automatically handled with the input details obtain from the customer identifying card. 8he regional system will report to the city (computer system of the city) while the city will report to the country (computer system of the cou ntry).
<#7@# What is the Data 3ccess Aayer? 8he data access layer (;A?)" which is a key part of e%ery n-tier system" is mainly consist of a simple set of code that does basic interactions with the database or an y other storage de%ice. 8hese functionalities are often referred to as C#M; (Create" #etrie%e" Mpdate" and ;elete). 8he data access layer need to be generic" simple" Puick and efficient as much as possible. It should not include comple& application7 business logics. I ha%e seen systems with lengthy" comple& store procedures ()" which run through se%eral cases before doing a simple retrie%al. 8hey contain not only most part of the business logic" but application logic and user interface logic as well. If is getting longer and complicated" then it is a good indication that you are burring your business logic inside the data access layer.
<#:8# What is the .usiness Aogic Aayer? I know for a fact that this is a Puestion for most" but from the other hand by reading many articles I ha%e become aware that not e%eryone agrees to what business logic actually is" and in many cases itFs just the bridge in between the presentation layer and the data access layer with ha%ing nothing much" e&cept taking from one and passing to the other. In some other cases" it is not e%en been well thought out" they just take the lefto%ers from the presentation layer and the data access layer then put them in another layer which automatically is called the business logic layer. $owe%er there are no god said things that
cannot be changed in software world. Bou can change as and when you feel comfortable that the method you apply is fle&ible enough to support the growth of your system. 8here are many great ways" but be careful when selecting them" they can o%er complicating the simple system. It is a balance one needs to find with their e&perience. As a general ad%ice when you define business entities" you must decide how to map the data in your tables to correctly defined business entities. 8he business entities should meaningfully define considering %arious types of rePuirements and functioning of your system. It is recommended to identify the business entities to encapsulate the functional7 MI (Mser Interface) rePuirements of your application" rather than define a separate business entity for each table of your database. or e&le" if you want to combine data from couple of table to build a MI (Mser Interface) control ('eb Control)" implement that function in the Kusiness ?ogic ?ayer with a business object that uses couple of data object to support with your comple& business rePuirement.
<#:9# What is )ang of $our %)o$& Design Patterns? 8he Gang of our (Go) patterns are generally considered the foundation for all other patterns. 8hey are categori*ed in three groups Creational" tructural" and Keha%ioral. $ere you will find information on these important patterns. Creational Patterns o o o o o
Abstract actory Creates an instance of se%eral families of classes Kuilder eparates object construction from its representation actory 0ethod Creates an instance of se%eral deri%ed classes rototype A fully initiali*ed instance to be copied or cloned ingleton A class of which only a single instance can e&ist
Structural Patterns o o o o o o o
Adapter 0atch interfaces of different classes Kridge eparates an object’s interface from its implementation Composite A tree structure of simple and composite objects ;ecorator Add responsibilities to objects dynamically acade A single class that represents an entire subsystem lyweight A fine-grained instance used for efficient sharing ro&y An object representing another object
.eha4ioral Patterns o o o o
Chain of #esp. A way of passing a rePuest between a chain of objects Command +ncapsulate a command rePuest as an object Interpreter A way to include language elements in a program Iterator ePuentially access the elements of a collection
o o o o o o o
0ediator ;efines simplified communication between classes 0emento Capture and restore an objectFs internal state @bser%er A way of notifying change to a number of classes tate Alter an objectFs beha%ior when its state changes trategy +ncapsulates an algorithm inside a class 8emplate 0ethod ;efer the e&act steps of an algorithm to a subclass !isitor ;efines a new operation to a class without change
<#:7# What is the difference between 3bstract $actory and .uilder design patterns? 8he two design patterns are fundamentally different. $owe%er" when you learn them for the first time" you will see a confusing similarity. o that it will make harder for you to understand them. Kut if you continue to study e%entually" you will get afraid of design patterns too. It is like infant phobia" once you get afraid at your early age" it stays with you fore%er. o the result would be that you ne%er look back at design patterns again. ?et me see whether I can sol%e this brain teaser for you. In the image below" you ha%e both design pa ttern listed in. I am trying to compare the two one on one to identify the similarities. If you obser%e the figure carefully" you will see an easily understandable color pattern (same color is used to mark the classes that are of similar kind).
lease follow up with the numbers in the image when reading the listing below. 0ark 29 Koth patterns ha%e used a generic class as the entry-class. 8he only difference is the name of the class. @ne pattern has named it as “Client”" while the other named it as “;irector”. 0ark 27 $ere again the difference is the class name. It is “ Abstractactory” for one and “Kuilder” for the other. Additionally both classes are of type abstract. 0ark 2: @nce again both patterns ha%e defined two generic ('indowsactory V ConcreteKuilder) classes. 8hey both ha%e created by inheriting their respecti%e abstract class. 0ark 2< inally" both seem to produce some kind of a generic output. 9ow" where are weQ Aren’t they looking almost identicalQ o then why are we ha%ing two different patterns hereQ ?et’s compare the two again side by side for one last time" but this time" focusing on the differences.
•
•
• •
•
•
•
•
• •
!bstract actory +mphasi*es a family of product objects (either simple or comple&) &uilder ocuses on constructing a comple& object step by step !bstract actory ocus on TwhatT is made &uilder ocus on ThowT it is made !bstract actory ocus on defining many different types of TfactoriesT to build many TproductsT" and it is not a one builder for just one product &uilder ocus on building a one comple& but one single TproductT !bstract actory ;efers the choice of what concrete type of object to make until run time &uilder $ide the logic7 operation of how to compile that comple& object !bstract actory T+%eryT method call creates and returns different objects &uilder @nly the TlastT method call returns the object" while other calls partially build the object
ometimes creational patterns are complementary o you can join one or many patterns when you design your system. As an e&le builder can use one of the other patterns to implement which components get built or in another case Abstract actory" Kuilder" and rototype can use ingleton in their implementations. o the conclusion would be that the two design patterns e&ist to resol%e two type of business problems" so e%en though they look similar" they are not. I hope that this shed some light to resol%e the pu**le. If you still don’t understand it" then this time it is not you" it has to be me and it is since that I don’t know how to e&plain it.
=# What is the Conclusion? I donFt think" that it is realistic trying to make a programming language be e%erything to e%erybody. 8he language becomes bloated" hard to learn" and hard to read if e%erything plus the kitchen sink is thrown in. In another word e%ery language has their limitations. As system architect and designer we should be able to fully and more importantly correctly (this also mean that you shouldn’t use a ballistic missile to kill a fly or h ire KI to catch the fly) utili*e the a%ailable tools and features to build usable" sustainable" maintainable and also %ery importantly e&pandable software systems" that fully utili*e the feature of the language to bring a competiti%ely ad%ance system to their customers. In order to do it" the foundation of a system places a %ital role. 8he design or the architecture of a software system is the foundation. It hold the system together" hence designing a system properly (this ne%er mean an To%erT desinging) is the key to the success. 'hen you talk about designing a software system" the correct handling of @@ concept is %ery important. I ha%e made the abo%e article richer with idea but still kept it short so that one can learn7 remind all of important concept at a glance. $ope you all will enjoy reading it.