Friday, August 9, 2013



OOPS Concepts:


  1. 1.OOPS:

  2. Object-oriented programming (OOP) is a programming language model organized around objects rather than "actions" and data rather than logic. Historically,a program has been viewed as a logical procedure that takes input data, processes it, and produces output data.

  3. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  4. 2.Class:

  5. Class is the collection of variables,methods and properties to specify various operations that can be performed to accomplish a task. Class does not occupy any memory space and hence it is only logical representation of data.
  6. Example:

  7. System;
  8. System.Collections.Generic;
  9. System.Linq;
  10. System.Text;
  11. oopsCode
  12. {
  13. Program
  14. {
  15. Main(string[] args)
  16. {
  17. Employee Emp = Employee();
  18. Emp.GetEmployeeSal();
  19. .ReadLine();
  20. }
  21. }
  22. Employee
  23. {
  24. dblEmpsal = 70000;
  25. GetEmployeeSal()
  26. {
  27. .WriteLine("Employee salary {0}", dblEmpsal);
  28. }
  29. }
  30. }
  31. ***********
  32. ***********
  33. OUTPUT :
  34. Employee salary 70000
  35. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  36. 3.Difference between class and struct:

  37. 1.Classes are Reference types and Structures are Values types.
  38. 2.Classes will support an Inheritance whereas Structures won’t
  39. 3.Classes can have explicitly parameter less constructors whereas structures can’t
  40. 4.Member variable initialization is possible in class whereas in Structures, it is not
  41. 5.It is not possible to declare destructor in structure but in class it is possible
  42. Example of point no. 1:

  43. System;
  44. System.Collections.Generic;
  45. System.Linq;
  46. System.Text;
  47. oopsCode
  48. {
  49. Program
  50. {
  51. Main(string[] args)
  52. {
  53. TestClass objTestClass1 = TestClass();
  54. objTestClass1.testVar=20;
  55. TestClass objTestClass2 =objTestClass1;
  56. objTestClass2.testVar = 30;
  57. .WriteLine("objTestClass1.testVar {0}", objTestClass1.testVar);
  58. .WriteLine("objTestClass2.testVar {0}", objTestClass2.testVar);
  59. TestClass objTestClass3 = TestClass();
  60. objTestClass3.testVar = 20;
  61. TestClass objTestClass4 = TestClass();
  62. objTestClass4.testVar = 30;
  63. .WriteLine("************");
  64. .WriteLine("objTestClass3.testVar {0}", objTestClass3.testVar);
  65. .WriteLine("objTestClass4.testVar {0}", objTestClass4.testVar);
  66. .ReadLine();
  67. }
  68. }
  69. TestClass
  70. {
  71. testVar;
  72. }
  73. }
  74. ***********
  75. ***********
  76. Output :
  77. objTestClass1.testVar 30
  78. objTestClass2.testVar 30
  79. ************
  80. objTestClass3.testVar 20
  81. objTestClass3.testVar 30
  82. System;
  83. System.Collections.Generic;
  84. System.Linq;
  85. System.Text;
  86. oopsCode
  87. {
  88. Program
  89. {
  90. Main(string[] args)
  91. {
  92. TestStructure objTestStructure1 = TestStructure();
  93. objTestStructure1.testVar = 20;
  94. TestStructure objTestStructure2 = objTestStructure1;
  95. objTestStructure2.testVar = 30;
  96. .WriteLine("objTestStructure1.testVar {0}", objTestStructure1.testVar);
  97. .WriteLine("objTestStructure2.testVar {0}", objTestStructure2.testVar);
  98. TestStructure objTestStructure3 = TestStructure();
  99. objTestStructure3.testVar = 20;
  100. TestStructure objTestStructure4 = TestStructure();
  101. objTestStructure4.testVar = 30;
  102. .WriteLine("************");
  103. .WriteLine("objTestStructure3.testVar {0}", objTestStructure3.testVar);
  104. .WriteLine("objTestStructure4.testVar {0}", objTestStructure4.testVar);
  105. .ReadLine();
  106. }
  107. }
  108. TestStructure
  109. {
  110. testVar;
  111. }
  112. }
  113. ***********
  114. ***********
  115. Output :
  116. objTestStructure1.testVar 20
  117. objTestStructure2.testVar 30
  118. ************
  119. objTestStructure3.testVar 20
  120. objTestStructure4.testVar 30

  121. When to Use Structure and Class?

  122. In general, classes can be used when you have more complex behavior or data. And if you think that these behavior or data to be modified after creating an instance of class, then classes are absolute methods.Structures can be used for small data structures. If developer feels that data members of structure cannot to be modified after creating structure, then having structure will suit

  123. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  124. 4.Object:

  125. It is a real time entity. It is an instance of a class
  126. Example:

  127. emp = ();

  128. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  129. 5.Abstraction:

  130. Abstraction is a process of hiding the implementation details and displaying the essential features

  131. Example of Abstraction:

  132. {
  133. doAbstraction();
  134. }
  135. Impl: Abstraction
  136. {
  137. doAbstraction()
  138. {
  139. //Implement it
  140. }
  141. }

  142. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  143. 6.Encapsulation:

  144. Encapsulation is the process of hiding the data into the single unit to protect the data from the outside world. Example of encapsulation is a class

  145. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  146. 7.Difference between Encapsulation and Abstraction in OOPS:

  147. 1.Encapsulation is the process of hiding the data using private and protected access modifier while abstraction is the process of hiding the data implementation
  148. 2.Abstraction is implemented using interface and abstract class while Encapsulation is implemented using private and protected access modifier

  149. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  150. 8.Access Specifiers:

  151. 1.Public: Accessible outside the class through object reference
  152. 2.Private: Accessible inside the class only through member functions
  153. 3.Protected: Just like private but Accessible in derived classes also through member functions
  154. 4.Internal: Visible inside the assembly. Accessible through objects
  155. 5.Protected Internal: Visible inside the assembly through objects and in derived classes outside the assembly through member functions

  156. Non-nested types (Default Access Specifiers):

  157. ---
    |
    Default
    |
    Permitted declablue accessibilities
    namespace
    |
    public
    |
    none (always implicitly public)
    enum
    |
    public
    |
    none (always implicitly public)
    interface
    |
    internal
    |
    public,internal
    class
    |
    internal
    |
    public,internal
    struct
    |
    internal
    |
    public,internal
    delegate
    |
    internal
    |
    public,internal
    abstract class
    |
    internal
    |
    public,internal
    class Method
    |
    private
    |
    public,internal ,private ,protected
    struct Method
    |
    private
    |
    public,internal,private,protected
    constructor
    |
    private
    |
    public,internal

  1. Nested type and member accessibilities (Default Access Specifiers):

  2. ---
    |
    Default
    |
    Permitted declablue accessibilities
    namespace
    |
    public
    |
    none (always implicitly public)
    enum
    |
    public
    |
    none (always implicitly public)
    interface
    |
    public
    |
    none
    class
    |
    private
    |
    All
    struct
    |
    private
    |
    public,internal,private
    delegate
    |
    private
    |
    All
    constructor
    |
    protected
    |
    All
    interface mem
    |
    public
    |
    none (always implicitly public)
    method
    |
    private
    |
    All
    field
    |
    private
    |
    All
    user-def operator
    |
    none
    |
    public (must be declablue public)

  1. Examples:

  2. abcStruct
  3. {
  4.  
  5. }
  6. Error: Elements defined in a namespace cannot be explicitly declablue as private, protected, or protected internal
  7. absClass
  8. {
  9.  
  10. }
  11. Error: Elements defined in a namespace cannot be explicitly declablue as private, protected, or protected internal

  12. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  13. 9.Access specifiers inside properties for set and get:

  14. We can set any access specifier for set or get but can not applied for both set and get simultaneously.

  15. Examples:

  16. {
  17. TheInt
  18. {
  19. ;
  20. }
  21. :
  22. {
  23. TheInt
  24. {
  25. ;
  26. ;
  27. }
  28. ()
  29. {
  30. TheInt = 123;
  31. }
  32. }
  33. }
  34. In this example, the interface has specified a getter, but not a setter. So when someone has an instance of the interface, they are only allowed to access the value, but cannot alter it.
  35. strProp1
  36. {
  37. ;
  38. ;
  39. }
  40. Can't specify accessibility modifier for both of the property.

  41. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  42. 10.Object And Instance:

  43. Variable for class is an object. When an object is created by using the keyword new, then memory will be allocated for the class in heap memory area, which is called as an instance

  44. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  45. 11.Can we use pointers in C#:

  46. To maintain type safety and security, C# does not support pointer arithmetic, by default. However, by using the unsafe keyword, you can define an unsafe context in which pointers can be used. It is just code whose safety cannot be verified by the CLR. The CLR will therefore only execute unsafe code if it is in a fully trusted assembly. If you use unsafe code, it is your responsibility to ensure that your code does not introduce security risks or pointer errors.
  47. A pointer type declaration takes one of the following forms:
  48. type* identifier;
  49. void* identifier; //allowed but not recommended;
  50. Any of the following types may be a pointer type:
  51. • sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.
  52. • Any enum type.
  53. • Any pointer type.
  54. • Any user-defined struct type that contains fields of unmanaged types only.
  55. boxing and unboxing do not support pointers. However, you can convert between different pointer types and between pointer types and integral types.
  56. When you declare multiple pointers in the same declaration, the asterisk (*) is written together with the underlying type only; it is not used as a prefix to each pointer name. For example:
  57. int* p1, p2, p3; // Ok
  58. int *p1, *p2, *p3; // Invalid in C#
  59. A pointer cannot point to a reference or to a struct that contains references, because an object reference can be garbage collected even if a pointer is pointing to it. The garbage collector does not keep track of whether an object is being pointed to by any pointer types.
  60. The value of the pointer variable of type myType* is the address of a variable of type myType. The following are examples of pointer type declarations:
  1. Example
    Description
    int* p
    p is a pointer to an integer.
    int** p
    p is a pointer to a pointer to an integer.
    int*[] p
    p is a single-dimensional array of pointers to integers.
    char* p
    p is a pointer to a char.
    void* p
    p is a pointer to an unknown type.
  1. int* myVariable;
  2. The expression *myVariable denotes the int variable found at the address contained in myVariable.
  3. // Normal pointer to an object.
  4. int[] a = new int[5] {10, 20, 30, 40, 50};
  5. // Must be in unsafe code to use interior pointers.
  6. unsafe
  7. {
  8. // Must pin object on heap so that it doesn't move while using interior pointers.
  9. (int* p = &a[0])
  10. {
  11. // p is pinned as well as object, so create another pointer to show incrementing it.
  12. int* p2 = p;
  13. .WriteLine(*p2);
  14. // Incrementing p2 bumps the pointer by four bytes due to its type ...
  15. p2 += 1;
  16. .WriteLine(*p2);
  17. p2 += 1;
  18. .WriteLine(*p2);
  19. .WriteLine("--------");
  20. .WriteLine(*p);
  21. // Deferencing p and incrementing changes the value of a[0] ...
  22. *p += 1;
  23. .WriteLine(*p);
  24. *p += 1;
  25. .WriteLine(*p);
  26. }
  27. }
  28. .WriteLine("--------");
  29. .WriteLine(a[0]);
  30. .ReadLine();
  31. // Output:
  32. //10
  33. //20
  34. //30
  35. //--------
  36. //10
  37. //11
  38. //12
  39. //--------
  40. //12
  41. You cannot apply the indirection operator to a pointer of type void*. However, you can use a cast to convert a void pointer to any other pointer type, and vice versa.
  42. A pointer can be null. Applying the indirection operator to a null pointer causes an implementation-defined behavior.
  43. Be aware that passing pointers between methods can cause undefined behavior. Examples are returning a pointer to a local variable through an Out or Ref parameter or as the function result. If the pointer was set in a fixed block, the variable to which it points may no longer be fixed.
  44. The following table lists the operators and statements that can operate on pointers in an unsafe context:
  1. Operator/Statement
    Use
    *
    Performs pointer indirection.
    ->
    Accesses a member of a struct through a pointer.
    []
    Indexes a pointer.
    &
    Obtains the address of a variable.
    ++ and --
    Increments and decrements pointers.
    + and -
    Performs pointer arithmetic.
    ==, !=, <, >, <=, and >=
    Compares pointers.
    stackalloc
    Allocates memory on the stack.
    fixed statement
    Temporarily fixes a variable so that its address may be found.

  1. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  2. 12.Inheritance:

  3. Creating a new class from an existing class is called as inheritance. Advantage of inheritance is reusability of the code.

  4. Example:

  5. SuperCar : car
  6. {
  7. }

  8. Inheritance can be classified to 5 types

  9. 1.Single Inheritance
  10. 2.Hierarchical Inheritance
  11. 3.Multi-Level Inheritance
  12. 4.Hybrid Inheritance
  13. 5.Multiple Inheritance

  14. 1.Single Inheritance

  15. When a single derived class is created from a single base class then the inheritance is called as single inheritance.
  16. BASE
  17. DERIVED

  18. 2.Hierarchical Inheritance

  19. When more than one derived class are created from a single base class, then that inheritance is called as hierarchical inheritance.
  20. BASE
  21. DERIVED1
    DERIVED1

  1. 3.Multi-Level Inheritance

  2. When a derived class is created from another derived class, then that inheritance is called as multi-level inheritance.
  3. BASE
  4. DERIVED1
  5. DERIVED2

  6. 4.Hybrid Inheritance

  7. Any combination of single, hierarchical and multi level inheritances is called as hybrid inheritance.
  8. BASE
  9. DERIVED1
  10. DERIVED1
    DERIVED1

  1. 5.Multiple Inheritances

  2. When a derived class is created from more than one base class then that inheritance is called as multiple inheritances. But multiple inheritances is not supported by .net using classes and can be done using interfaces.
  3. BASE1
    BASE2
  1. DERIVED

  1. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  2. 13.Why multiple inheritance is not possible in c#

  3. In C++, what’s the diamond problem, and how can it be avoided?
  4. Taking a look at the graphic below helps in explaining the diamond problem.
  5. B==>A<==C , B<==D==>C
  6. Suppose we have 2 classes B and C that derive from the same class – in our example above it would be class A. We also have class D that derives from both B and C by using multiple inheritance. You can see in the figure above that the classes essentially form the shape of a diamond – which is why this problem is called the diamond problem. Now, let’s take the graphic above and make it more concrete by translating it into actual code:
  7. /*
  8. The Animal class below corresponds to class
  9. A in our graphic above
  10. */
  11. /*
  12. class Animal { /* ... */ }; // base class
  13. {
  14. int weight;
  15. public:
  16. int getWeight() { return weight;};
  17. public:
  18. public:
  19. };
  20. class Tiger : public Animal { /* ... */ };
  21. class Lion : public Animal { /* ... */ }
  22. class Liger : public Tiger, public Lion { /* ... */ };
  23. In the code above, we’ve given a more concrete example of the diamond problem. The Animal class corresponds to the topmost class in the hierarchy (A in our graphic above), Tiger and Lion respectively correspond to B and C in the graphic, and the Liger class corresponds to D.
  24. Now, the question is what is the problem with having an inheritance hierarcy like this. Take a look at the code below so that we can best answer that question:
  25. main( )
  26. {
  27. lg ;
  28. /*COMPILE ERROR, the code below will not past
  29. any C++ compiler */
  30. weight = lg.Weight();
  31. }
  32. In our inheritance hierarchy, we can see that both the Tiger and Lion classes derive from the Animal base class. And here is the problem: because Liger derives from both the Tiger and Lion classes – which each have their own copy of the data members and methods of the Animal class- the Liger object "lg" will contain two subobjects of the Animal base class.
  33. So, you ask, what’s the problem with a Liger object having 2 sub-objects of the Animal class? Take another look at the code above – the call "lg.getWeight()" will result in a compiler error. This is because the compiler does not know whether the call to getWeight refers to the copy of getWeight that the Liger object lg inherited through the Lion class or the copy that lg inherited through the Tiger class. So, the call to getWeight in the code above is ambiguous and will not get past the compiler.

  34. Solution to the Diamond Problem

  35. We’ve given an explanation of the diamond problem, but now we want to give you a solution to the diamond problem. If the inheritance from the Animal class to both the Lion class and the Tiger class is marked as virtual, then C++ will ensure that only one subobject of the Animal class will be created for every Liger object. This is what the code for that would look like:
  36. class Tiger : virtual public Animal { /* ... */ };
  37. class Lion : virtual public Animal { /* ... */ }
  38. You can see that the only change we’ve made is to add the "virtual" keyword to the Tiger and Lion class declarations. Now the Liger class object will have only one Animal subobject, and the code below will compile just fine:
  39. int main( )
  40. {
  41. /*THIS CODE WILL NOW COMPILE OK NOW THAT WE'VE USED THE VIRTUAL KEYWORD IN THE TIGER AND LION CLASS DECLARATIONS */
  42. int weight = lg.getWeight();
  43. }
  44. Multiple inheritance problem is solved by interfaces in c#
  45. {
  46. aa();
  47. }
  48. {
  49. aa();
  50. }
  51. : ,
  52. {
  53. .aa()
  54. {
  55. }
  56. .aa()
  57. {
  58. }
  59. }

  60. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  61. 14.Method Hiding

  62. If you want your derived member to have the same name as a member in a base class, but you do not want it to participate in virtual invocation, you can use the new keyword. The new keyword is put before the return type of a class member that is being replaced.
  63. The child class is hiding the base class method. This is called method hiding

  64. Example:

  65. System;
  66. {
  67. Write ()
  68. {
  69. .WriteLine (" Class write method");
  70. }
  71. }
  72. :
  73. {
  74. Write ()
  75. {
  76. .WriteLine (" Class write method");
  77. }
  78. Ma ()
  79. {
  80. C1 = ();
  81. C1.Write (); // Calls the method => Class write method
  82. (() C1).Write ();//Type caste C1 to be of type and call Write ()
  83. Method=> Class write method
  84. P1 = ()C1;
  85. P1.Write(); // Calls the old method=> Class write method
  86. P1 = ();
  87. P1.Write(); // Calls the old method=> Class write method
  88. P1 = ();
  89. P1.Write();// Error: Cannot implicitly convert type to
  90. .
  91. }
  92. }

  93. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  94. 15.Polymorphism:

  95. Polymorphism means having more than one form. An operation that exhibit different behavior On different situation.Polymorphism can be achieved with the help of overloading and overriding concepts. Polymorphism is classified into compile time polymorphism and runtime polymorphism.
  96. It has two distinct aspects:
  97. 1.At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.
  98. 2.Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.

  99. Polymorphism is of two types:

  100. 1.Compile time polymorphism/Overloading
  101. 2.Runtime polymorphism/Overriding

  102. 1.Compile Time Polymorphism

  103. Compile time polymorphism is method overloading. It is also called early binding.In method overloading method performs the different task at the different input parameters. It is also defined as same name method with different signature.

  104. 2.Runtime Time Polymorphism

  105. Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding. When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype.

  106. Method Overloading

  107. It is the same name method with different signature

  108. Example:

  109. Area(l, b)
  110. {
  111. x = ()l* b;
  112. // here we have used function overload with 2 parameters.
  113. .WriteLine ("Area of a rectangle: {0}",x);
  114. }
  115. Area(a, b, c)
  116. {
  117. s = ()(a*b*c)/2;
  118. // here we have used function overload with 3 parameters.
  119. .WriteLine ("Area of a circle: {0}", s);
  120. }
  121. Method Overriding

  122. Overriding means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by using virtual/override keywords.

  123. Example

  124. // Base class
  125. {
  126. Method1()
  127. {
  128. .Write("Base Class Method");
  129. }
  130. }
  131. // Derived class
  132. :
  133. {
  134. void Method1()
  135. {
  136. .Write("Derived Class Method");
  137. }
  138. }
  139. // Using base and derived class
  140. {
  141. TestMethod()
  142. {
  143. //calling the overriden method
  144. objDC = new ();
  145. objDC.Method1();
  146. //calling the baesd class method
  147. objBC = ()objDC;
  148. objDC.Method1();
  149. }
  150. }
  151. {
  152. // A few example members
  153. X
  154. {
  155. ; ;
  156. }
  157. Y
  158. {
  159. ; ;
  160. }
  161. Height
  162. {
  163. ; ;
  164. }
  165. Width
  166. {
  167. ; ;
  168. }
  169. // Virtual method
  170. Draw()
  171. {
  172. .WriteLine("Performing drawing tasks");
  173. }
  174. }
  175. Circle :
  176. {
  177. Draw()
  178. {
  179. // Code to draw a circle...
  180. .WriteLine("Drawing a circle");
  181. base.Draw();
  182. }
  183. }
  184. :
  185. {
  186. Draw()
  187. {
  188. // Code to draw a rectangle...
  189. .WriteLine("Drawing a rectangle");
  190. base.Draw();
  191. }
  192. }
  193. Triangle :
  194. {
  195. Draw()
  196. {
  197. // Code to draw a triangle...
  198. .WriteLine("Drawing a triangle");
  199. base.Draw();
  200. }
  201. }
  202. Program
  203. {
  204. Main(string[] args)
  205. {
  206. // Polymorphism at work #1: a , Triangle and Circle
  207. // can all be used whereever a expected. No cast
  208. // required because an conversion exists from a derived
  209. // to its class.
  210. System.Collections.Generic.List<> shapes = System.Collections.Generic.List<>();
  211. shapes.Add( ());
  212. shapes.Add( Triangle());
  213. shapes.Add( Circle());
  214. // Polymorphism at work #2: the method Draw
  215. // invoked on each of the derived classes, not the class.
  216. ( s shapes)
  217. {
  218. s.Draw();
  219. }
  220. // Keep the console open debug mode.
  221. .WriteLine("Press any key to exit.");
  222. .ReadKey();
  223. }
  224. }
  225. /* Output:
  226. Drawing a rectangle
  227. Performing drawing tasks
  228. Drawing a triangle
  229. Performing drawing tasks
  230. Drawing a circle
  231. Performing drawing tasks
  232. */
  233. Program
  234. {
  235. Main(string[] args)
  236. {
  237. System.Collections.Generic.List<> shapes = System.Collections.Generic.List<>();
  238. shapes.Add( ());
  239. shapes.Add( Circle());
  240. // Polymorphism at work #2: the method Draw
  241. // invoked on each of the derived classes, not the class.
  242. ( s shapes)
  243. {
  244. s.Draw();
  245. }
  246. // Keep the console open debug mode.
  247. .WriteLine("Press any key to exit.");
  248. .ReadKey();
  249. .ReadLine();
  250. }
  251. }
  252. {
  253. // A few example members
  254. X
  255. {
  256. ; ;
  257. }
  258. Y
  259. {
  260. ; ;
  261. }
  262. Height
  263. {
  264. ; ;
  265. }
  266. Width
  267. {
  268. ; ;
  269. }
  270. // Virtual method
  271. Draw()
  272. {
  273. .WriteLine("Performing drawing tasks");
  274. }
  275. }
  276. Circle :
  277. {
  278. Draw()
  279. {
  280. // Code to draw a circle...
  281. .WriteLine("Drawing a circle");
  282. base.Draw();
  283. }
  284. }
  285. : Circle
  286. {
  287. Draw()
  288. {
  289. // Code to draw a rectangle...
  290. .WriteLine("Drawing a rectangle");
  291. base.Draw();
  292. }
  293. }
  294. OUTPUT:
  295. Drawing a rectangle
  296. Drawing a circle
  297. Performing drawing tasks
  298. Drawing a circle
  299. Performing drawing tasks
  300. Virtual Members

  301. When a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base class. The designer of the derived class can choose whether to
  302. •override virtual members in the base class,
  303. •inherit the closest base class method without overriding it
  304. •define new non-virtual implementation of those members that hide the base class implementations
  305. A derived class can override a base class member only if the base class member is declared as virtual or abstract. The derived member must use the override keyword to explicitly indicate that the method is intended to participate in virtual invocation
  306. Example
  307. Program
  308. {
  309. Main(string[] args)
  310. {
  311. B = ();
  312. B.DoWork(); // Calls the method.
  313. A = ()B;
  314. A.DoWork(); // Also calls the method.
  315. A1 = ();
  316. A.DoWork();
  317. // A2 = ();
  318. //A.DoWork();
  319. .ReadLine();
  320. }
  321. }
  322. {
  323. DoWork()
  324. {
  325. .WriteLine("");
  326. }
  327. WorkProperty
  328. {
  329. {
  330. 0;
  331. }
  332. }
  333. }
  334. :
  335. {
  336. DoWork()
  337. {
  338. .WriteLine("");
  339. }
  340. WorkProperty
  341. {
  342. {
  343. 0;
  344. }
  345. }
  346. }
  347. Output:

  348. Preventing Derived Classes from Overriding Virtual Members

  349. A derived class can stop virtual inheritance by declaring an override as sealed. This requires putting the sealed keyword before the override keyword in the class member declaration.
  350. Example
  351. A
  352. {
  353. DoWork()
  354. {
  355. }
  356. }
  357. B : A
  358. {
  359. DoWork()
  360. {
  361. }
  362. }
  363. C : B
  364. {
  365. DoWork()
  366. {
  367. }
  368. }
  369. In the above example, the method DoWork is no longer virtual to any class derived from C. It is still virtual for instances of C, even if they are cast to type B or type A. Sealed methods can be replaced by derived classes by using the new keyword, as the following example shows:
  370. D : C
  371. {
  372. DoWork()
  373. {
  374. }
  375. }

  376. Accessing Base Class Virtual Members from Derived Classes

  377. A derived class that has replaced or overridden a method or property can still access the method or property on the base class using the base keyword.
  378. Example
  379. Base
  380. {
  381. DoWork()
  382. {
  383. /*...*/
  384. }
  385. }
  386. Derived : Base
  387. {
  388. DoWork()
  389. {
  390. //Perform Derived's work here
  391. //...
  392. // Call DoWork on
  393. base.DoWork();
  394. }
  395. }

  396. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  397. 16.Cohesion and Coupling :


  398. Cohesion

  399. The concept of cohesion shows to what degree a program’s or a component’s various tasks and responsibilities are related to one another, i.e. how much a program is focused on solving a single problem. Cohesion is divided into strong cohesion and weak cohesion.

  400. Strong Cohesion

  401. Strong cohesion indicates that the responsibilities and tasks of a piece of code (a method, class, component or a program) are related to one another and intended to solve a common problem. This is something we must always aim for. Strong cohesion is a typical characteristic of high-quality software.

  402. Strong Cohesion in a Class

  403. Strong cohesion in a class indicates that the class defines only one entity. We mentioned earlier that an entity can have many roles (Peter is a soldier, husband and a taxpayer). Each of these roles is defined in the same class. Strong cohesion indicates that the class solves only one task, one problem, and not many at the same time.
  404. A class, which does many things at the same time, is difficult to understand and maintain. Consider a class, which implements a hash table, provides functions for printing, sending an e-mail and working with trigonometric functions all at once. How do we name such a class? If we find it difficult to answer this question, this means that we have failed to achieve strong cohesion and have to separate the class into several smaller classes, each solving a single task.

  405. Strong Cohesion in a Class – Example

  406. As an example of strong cohesion we can point out the System.Math class. It performs a single task: it provides mathematical calculations and constants:
  407. - Sin(), Cos(), Asin()
  408. - Sqrt(), Pow(), Exp()
  409. - Math.PI, Math.E

  410. Strong Cohesion in a Method

  411. A method is well written when it performs only one task and performs it well. A method, which does a lot of work related to different things, has bad cohesion. It has to be broken down into simpler methods, each solving only one task. Once again, the question is posed what name should we give to a method, which finds prime numbers, draws 3D graphics on the screen, communicates with the network and prints records extracted from a data base? Such a method has bad cohesion and has to be logically separated into several methods.

  412. Weak Cohesion

  413. Weak cohesion is observed along with methods, which perform several unrelated tasks. Such methods take several different groups of parameters, in order to perform different tasks. Sometimes, this requires logically unrelated data to be unified for the sake of such methods. Weak cohesion is harmful and must be avoided!

  414. Weak Cohesion – Example

  415. Here is a sample class with weak cohesion:
  416. {
  417. PrintDocument(Document d) { … }
  418. SendEmail(string recipient,
  419. string subject, string text) { … }
  420. CalculateDistanceBetweenPoints(
  421. int x1, int y1, int x2, int y2) { … }
  422. }

  423. Best Practices with Cohesion

  424. Strong cohesion is quite logically the "good" way of writing code. The concept is associated with simpler and clearer source code – code that is easier to maintain and reuse (because of the fewer tasks it has to perform).
  425. Contrarily, with weak cohesion each change is a ticking time bomb, because it could affect other functionality. Sometimes a logical task is spread out to several different modules and thus changing it is more labor intensive. Code reuse is also difficult, because a component does several unrelated tasks and to reuse it the exact same conditions must be met which is hard to achieve.

  426. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  427. 17.Coupling

  428. Coupling mostly describes the extent to which components / classes depend on one another. It is broken down into loose coupling and tight coupling. Loose coupling usually correlates with strong cohesion and vice versa.

  429. 1.Loose Coupling

  430. Loose coupling is defined by a piece of code’s (program / class / component) communication with other code through clearly defined interfaces (contracts). A change in the implementation of a loosely coupled component doesn’t reflect on the others it communicates with. When you write source code, you must not rely on inner characteristics of components (specific behavior that is not described by interfaces).
  431. The contract has to be maximally simplified and define only the requiblue behavior for this component’s work by hiding all unnecessary details.
  432. Loose coupling is a code characteristic you should aim for. It is one of the characteristics of high-quality programming code.

  433. Loose Coupling – Example

  434. Here is an example of loose coupling between classes and methods:
  435. {
  436. LoadFromFile(string fileName) { … }
  437. SaveToFile(string fileName) { … }
  438. }
  439. {
  440. Print(Report report) { … }
  441. }
  442. {
  443. Main()
  444. {
  445. myReport = new ();
  446. myReport.LoadFromFile("DailyReport.xml");
  447. .Print(myReport);
  448. }
  449. }
  450. In this example, none of the methods depend on the others. The methods rely only on some of the parameters, which are passed to them. Should we need one of the methods in a next project, we could easily take it out and reuse it.

  451. 2.Tight Coupling

  452. We achieve tight coupling when there are many input parameters and output parameters; when we use undocumented (in the contract) characteristics of another component (for example, a dependency on static fields in another class); and when we use many of the so called control parameters that indicate behavior with actual data. Tight coupling between two or more methods, classes or components means that they cannot work independently of one another and that a change in one of them will also affect the rest. This leads to difficult to read code and big problems with its maintenance.

  453. Tight Coupling – Example

  454. Here is an example of tight coupling between classes and methods:
  455. {
  456. operand;
  457. result;
  458. }
  459. {
  460. Sqrt()
  461. {
  462. .result = CalcSqrt(.operand);
  463. }
  464. }
  465. {
  466. Main()
  467. {
  468. .operand = 64;
  469. .Sqrt();
  470. .WriteLine(.result);
  471. }
  472. }
  473. Such code is difficult to understand and maintain, and the likelihood of mistakes when using it is great. Think about what happens if another method, which calls Sqrt(), passes its parameters through the same static variables operand and result.
  474. If we have to use the same functionality for deriving square root in a subsequent project, we will not be able to simply copy the method Sqrt(), but rather we will have to copy the classes MathParams and MathUtil together with all of their methods. This makes the code difficult to reuse.
  475. In fact, the above code is an example of bad code according to all rules of Procedural and Object-Oriented Programming and if you think twice, you will certainly identify at least several more disregarded recommendations from those we have given you so far.

  476. Best Practices with Coupling

  477. The most common and advisable way of invoking a well written module’s functionality is through interfaces. That way, the functionality can be substituted without clients of the code requiring changes. The jargon expression for this is "programming against interfaces".
  478. Most commonly, an interface describes a "contract" observed by this module. It is good practice not to rely on anything else other than what’s described by this contract. The use of inner classes, which are not part of the public interface of a module, is not recommended because their implementation can be substituted without substituting the contract (we already discussed this in the section "Abstraction").
  479. It is good practice that the methods are made flexible and ready to work with all components, which observe their interfaces, and not only with definitive ones (i.e. to have implicit requirements). The latter would mean that these methods expect something specific from the components they can work with. It is also good practice that all dependencies are clearly described and visible. Otherwise, the maintenance of such code becomes difficult (it is riddled with stumbling-blocks).
  480. A good example of strong cohesion and loose coupling we can find in the classes from the standard namespaces System.Collections and System.Collections.Generic. These .NET classes for working with collections have strong cohesion. Each solves a single problem and allows easy reuse. These classes have another characteristic of high-quality programming code: loose coupling. The classes, implementing the collections, are not related to one another. Each works through a strictly defined interface and does not give away details of its implementation. All methods and fields not from the interface are hidden, in order to blueuce the possibility of coupling with them. Methods in the collection classes do not depend on static variables and do not rely on any input data except for their inner state and passed parameters. This is good practice every programmer sooner or later attains with gained experience.

  481. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  482. 18.Constructors and Destructors:

  483. Constructors have the same name as the class or struct, and they usually initialize the data members of the new object. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
  484. 1.Constructors and destructors do not have return types nor can they return values.
  485. 2.References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
  486. 3.Constructors cannot be declared with the keyword virtual.
  487. 4.Constructors and destructors cannot be declared const, or volatile.
  488. 5.Unions cannot contain class objects that have constructors or destructors.
  489. The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object it’s this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor.

  490. Example of Constructor

  491. C
  492. {
  493. x;    
  494. y;
  495. C (i, j)
  496. {
  497. x = i;
  498. y = j;
  499. }
  500. display ()     
  501. {
  502. .WriteLine(x + "i+" + y);
  503. }
  504. }

  505. Example of Destructor

  506. D
  507. {
  508. D ()
  509. {
  510. // constructor
  511. }         
  512. ~D ()
  513. {
  514. // Destructor
  515. }
  516. }
  517. The class parameterized constructor can invoke the constructor of the base class through the initializer, as follows:
  518. Circle :
  519. {
  520. Circle(radius): base(radius, 0)
  521. {
  522. }
  523. }

  524. The order in which the object’s fields and constructors are initialized:

  525. 1.Derived static fields
  526. 2.Derived static constructor
  527. 3.Derived instance fields
  528. 4.Base static fields
  529. 5.Base static constructor
  530. 6.Base instance fields
  531. 7.Base instance constructor
  532. 8.Derived instance constructor

  533. Example:

  534. System;
  535. ObjectInit
  536. {
  537. Program
  538. {
  539. Main( string[] args )
  540. {
  541. Derived d = Derived();
  542. .ReadLine();
  543. }
  544. }
  545. Base
  546. {
  547. Base()
  548. {
  549. .WriteLine( "Base.Instance.Constructor" );
  550. this.m_Field3 = ( "Base.Instance.Field3");
  551. this.Virtual();
  552. }
  553. Base()
  554. {
  555. .WriteLine( "Base.Static.Constructor" );
  556. }
  557. m_Field1 = ("Base.Instance.Field1" );
  558. m_Field2 = ("Base.Instance.Field2" );
  559. m_Field3;
  560. s_Field1 = ( "Base.Static.Field1");
  561. s_Field2 = ( "Base.Static.Field2");
  562. Virtual()
  563. {
  564. .WriteLine( "Base.Instance.Virtual" );
  565. }
  566. }
  567. Derived : Base
  568. {
  569. Derived()
  570. {
  571. .WriteLine( "Derived.Instance.Constructor" );
  572. this.m_Field3 = ( "Derived.Instance.Field3" );
  573. }
  574. Derived()
  575. {
  576. .WriteLine( "Derived.Static.Constructor" );
  577. }
  578. m_Field1 = ( "Derived.Instance.Field1" );
  579. m_Field2 = ( "Derived.Instance.Field2" );
  580. m_Field3;
  581. s_Field1=("Derived.Static.Field1");
  582. s_Field2=("Derived.Static.Field2" );
  583. Virtual()
  584. {
  585. .WriteLine( "Derived.Instance.Virtual" );
  586. }
  587. }
  588. {
  589. ( text )
  590. {
  591. .WriteLine( text );
  592. }
  593. }
  594. }
  595. Following is the console output from this sample program:
  596. Derived.Static.Field1
  597. Derived.Static.Field2
  598. Derived.Static.Constructor
  599. Derived.Instance.Field1
  600. Derived.Instance.Field2
  601. Base.Static.Field1
  602. Base.Static.Field2
  603. Base.Static.Constructor
  604. Base.Instance.Field1
  605. Base.Instance.Field2
  606. Base.Instance.Constructor
  607. Base.Instance.Field3
  608. Derived.Instance.Virtual
  609. Derived.Instance.Constructor
  610. Derived.Instance.Field3

  611. Types of Constructors:

  612. 1.Instance Constructor
  613. 2.Private Constructor
  614. 3.Static Constructor

  615. 1.Instance Constructor:

  616. Instance constructors are used to create and initialize any instance member variables when you use the new expression to create an object of a class.

  617. Example:

  618. CoOrds
  619. {
  620. public x, y;
  621. // constructor 
  622. CoOrds()
  623. {
  624. x = 0;
  625. y = 0;
  626. }
  627. }

  628. 2.Private Constructor:

  629. It is generally used in classes that mostly contain static members only , it can contain non static methods but that cannot be called from outside the class. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class. Private constructors are used to prevent creating instances of a class when there are no instance fields or methods
  630. Note:
  631. If you do not use an access modifier with the constructor it will still be private by default

  632. Example:

  633. {
  634. // Private Constructor:
  635. NLog() { }
  636. e = Math.E; //2.71828...
  637. }

  638. NOTE:

  639. During inheritance, if the base class contains only parameterized constructor, then derived class must contain a parameterized constructor even it doesn’t need one.
  640. If we tried to access any member of the class where constructor is private then it will show compilation error. Can’t access the member because of protection level.

  641. 3.Static Constructor:

  642. A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
  643. Example

  644. SimpleClass
  645. {
  646. SimpleClass()
  647. {
  648. .WriteLine(“SimpleClass constructor called");
  649. .ReadLine();
  650. }
  651. cc()
  652. {
  653. .WriteLine("CC called");
  654. .ReadLine();
  655. }
  656. }
  657. Suppose we are creating the two objects of class SimpleClass.The constructor will call once.
  658. Example with output :
  659. SimpleClass objSimpleClass = new SimpleClass ();objSimpleClass.cc();
  660. SimpleClass objSimpleClass = new SimpleClass();objSimpleClass.cc();
  661. Output:
  662. SimpleClass constructor called
  663. CC called
  664. CC called

  665. How to: Write a Copy Constructor

  666. The Person class defines a copy constructor that takes, as its argument, an instance of Person. The values of the properties of the argument are assigned to the properties of the new instance of Person. The code contains an alternative copy constructor that sends the Name and Age properties of the instance that you want to copy to the instance constructor of the class.

  667. Person
  668. {
  669. // Copy constructor. 
  670. Person(Person previousPerson)
  671. {
  672. Name = previousPerson.Name;
  673. Age = previousPerson.Age;
  674. }
  675. // Instance constructor. 
  676. Person(name, age)
  677. {
  678. Name = name;
  679. Age = age;
  680. }
  681. public Age
  682. {
  683. ;
  684. ;
  685. }
  686. public Name
  687. {
  688. ;
  689. }
  690. public Details()
  691. {
  692. Name + " " + Age.ToString();
  693. }
  694. }
  695. TestPerson
  696. {
  697. static Main()
  698. {
  699. // Create a Person by the instance constructor.
  700. Person person1 = Person("George", 40);
  701. // Create another Person object, copying person1.
  702. Person person2 = Person(person1);
  703. // Change each person's age.
  704. person1.Age = 39;
  705. person2.Age = 41;
  706. // Change person2's name.
  707. person2.Name = "Charles";
  708. // Show details to verify that the name and age fields are distinct.
  709. .WriteLine(person1.Details());
  710. .WriteLine(person2.Details());
  711. // Keep the console window open debug mode.
  712. .WriteLine("Press any key to exit.");
  713. .ReadKey();
  714. }
  715. }
  716. // Output:
  717. // George is 39
  718. // Charles is 41

  719. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  720. 19.Abstract Classes and Abstract Methods in C#.NET:

  721. 1.Abstract Class:

  722. Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.
  723. Example:

  724. absClass
  725. {
  726. }

  727. A sample program that explains abstract classes:
  728. using System;
  729. namespace abstractSample
  730. {
  731. //Creating an Abstract Class
  732. absClass
  733. {
  734. //A Non abstract method
  735. public int AddTwoNumbers(int Num1, int Num2)
  736. {
  737. return Num1 + Num2;
  738. }
  739. //An abstract method, to be
  740. //overridden in derived class
  741. public abstract int MultiplyTwoNumbers(int Num1, int Num2);
  742. }
  743. absClass
  744. {
  745. //A Non abstract method
  746. public int AddTwoNumbers(int Num1, int Num2)
  747. {
  748. return Num1 + Num2;
  749. }
  750. //An abstract method, to be
  751. //overridden in derived class
  752. public abstract int MultiplyTwoNumbers(int Num1, int Num2);
  753. }
  754. }
  755. 2.Abstract properties:

  756. //Abstract Class with abstract properties
  757. absClass
  758. {
  759. myNumber;
  760. numbers
  761. {
  762. }
  763. }

  764. : absClass
  765. {
  766. //Implementing properties
  767. numbers
  768. {
  769. {
  770. myNumber;
  771. }
  772. {
  773. myNumber = value;
  774. }
  775. }
  776. }

  777. 3.Important rules applied to abstract classes

  778. //Incorrect
  779. //An abstract class cannot be a sealed class
  780. absClass
  781. {
  782. }
  783. //Incorrect
  784. //An abstract method cannot be private.
  785. MultiplyTwoNumbers();
  786. //Incorrect
  787. //An abstract method cannot have the modifier virtual. Because an abstract method is implicitly //virtual.
  788. MultiplyTwoNumbers();
  789. //Incorrect
  790. //An abstract member cannot be static.
  791. MultiplyTwoNumbers();

  792. Note:

  793. It is mandatory to override abstract method in the derived class.
  794. It is mandatory to give defination to non abstract method in abstract class.
  795. Abstract class can have Variables and properties.

  796. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  797. 20.Interface

  798. Interface is a type which contains only the signatures of methods, delegates or events, it has no implementation. Implementation of the methods is done by the class that which implements the interface. It provides a way to achieve runtime polymorphism.

  799. An interface has the following properties:
  800. •An interface is like an abstract base class. Any class or struct that implements the interface must implement all its members.
  801. •An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface.
  802. •Interfaces can contain events, indexers, methods, and properties.
  803. •Interfaces contain no implementation of methods.
  804. •A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.
  805. •Datatype variable can not be declared on abstract.(Ex. Public abstract int i;).

  806. Program1

  807. {
  808. Main()
  809. {
  810. System..WriteLine();
  811. }
  812. }
  813. {
  814. x;
  815. }
  816. output
  817. P1.cs(11,3): error CS0525: Interfaces cannot contain fields

  818. Program2


  819. {
  820. Main()
  821. {
  822. System..WriteLine("Hello Interfaces");
  823. }
  824. }
  825. {
  826. xyz()
  827. {
  828. System..WriteLine("In xyz");
  829. }
  830. }
  831. P2.cs(11,8): error CS0531: '.xyz()': members cannot have a
  832. inition

  833. Program3


  834. {
  835. Main()
  836. {
  837. System..WriteLine("Hello Interfaces");
  838. }
  839. }
  840. {
  841. xyz();
  842. }
  843. Hello Interfaces

  844. Program4


  845. :
  846. {
  847. Main()
  848. {
  849. System..WriteLine("Hello Interfaces");
  850. }
  851. }
  852. {
  853. xyz();
  854. }
  855. Output
  856. P4.cs(1,7): error CS0535: '' does not implement member
  857. '.xyz()'
  858. P4.cs(11,8): (Location of symbol related to previous error)

  859. Program5


  860. :
  861. {
  862. Main()
  863. {
  864. System..WriteLine("Hello Interfaces");
  865. }
  866. xyz()
  867. {
  868. System..WriteLine("In xyz");
  869. }
  870. }
  871. {
  872. xyz();
  873. }
  874. Output
  875. a.cs(1,7): error CS0536: '' does not implement member
  876. '.xyz()'.'.xyz()' either static, not public,
  877. or h the wrong type.
  878. a.cs(16,8): (Location of symbol related to previous error)
  879. a.cs(7,8): (Location of symbol related to previous error)

  880. Program6


  881. :
  882. {
  883. Main()
  884. {
  885. System..WriteLine("Hello Interfaces");
  886. xyz();
  887. }
  888. xyz()
  889. {
  890. System..WriteLine("In xyz");
  891. }
  892. }
  893. {
  894. xyz();
  895. }
  896. Output
  897. Hello Interfaces
  898. In xyz

  899. Program7


  900. :
  901. {
  902. Main()
  903. {
  904. System..WriteLine("Hello Interfaces");
  905. ref = ();
  906. ref.xyz();
  907. ref = ();
  908. ref.xyz();
  909. }
  910. xyz()
  911. {
  912. System..WriteLine("In :: xyz");
  913. }
  914. }
  915. {
  916. xyz();
  917. }
  918. :
  919. {
  920. xyz()
  921. {
  922. System..WriteLine("In :: xyz");
  923. }
  924. }
  925. Output
  926. In :: xyz
  927. In :: xyz

  928. Program8


  929. :
  930. {
  931. Main()
  932. {
  933. System..WriteLine("Hello Interfaces");
  934. ref = ();
  935. ref.xyz();
  936. ref = ();
  937. ref.xyz();
  938. }
  939. xyz()
  940. {
  941. System..WriteLine("In :: xyz");
  942. }
  943. }
  944. {
  945. xyz();
  946. }
  947. :
  948. {
  949. xyz()
  950. {
  951. System..WriteLine("In :: xyz");
  952. }
  953. }
  954. Output
  955. In :: xyz
  956. In :: xyz

  957. Program9


  958. :
  959. {
  960. Main()
  961. {
  962. [] ref = { (), () };
  963. (i = 0; i <= 1; i++)
  964. ref[i].xyz();
  965. }
  966. xyz()
  967. {
  968. System..WriteLine("In :: xyz");
  969. }
  970. }
  971. {
  972. xyz();
  973. }
  974. :
  975. {
  976. xyz()
  977. {
  978. System..WriteLine("In :: xyz");
  979. }
  980. }
  981. Output
  982. In :: xyz
  983. In :: xyz

  984. Program10


  985. : ,
  986. {
  987. Main()
  988. {
  989. System..WriteLine("Hello Interfaces");
  990. ref = ();
  991. ref.xyz();
  992. }
  993. xyz()
  994. {
  995. System..WriteLine("In xyz");
  996. }
  997. pqr()
  998. {
  999. System..WriteLine("In xyz");
  1000. }
  1001. }
  1002. {
  1003. xyz();
  1004. }
  1005. {
  1006. pqr();
  1007. }
  1008. Output
  1009. Hello Interfaces
  1010. In xyz

  1011. Program11


  1012. : ,
  1013. {
  1014. Main()
  1015. {
  1016. System..WriteLine("Hello Interfaces");
  1017. ref = ();
  1018. ref.xyz();
  1019. ref.pqr();
  1020. }
  1021. xyz()
  1022. {
  1023. System..WriteLine("In xyz");
  1024. }
  1025. pqr()
  1026. {
  1027. System..WriteLine("In xyz");
  1028. }
  1029. }
  1030. {
  1031. xyz();
  1032. }
  1033. {
  1034. pqr();
  1035. }
  1036. Output
  1037. P11.cs(9,5): error CS0117: '' does not contaa inition 'pqr'

  1038. Program12


  1039. : ,
  1040. {
  1041. Main()
  1042. {
  1043. System..WriteLine("Hello Interfaces");
  1044. ref = ();
  1045. ref = ref;
  1046. ref.xyz();
  1047. ref = ref;
  1048. ref.pqr();
  1049. }
  1050. xyz()
  1051. {
  1052. System..WriteLine("In xyz");
  1053. }
  1054. pqr()
  1055. {
  1056. System..WriteLine("In pqr");
  1057. }
  1058. }
  1059. {
  1060. xyz();
  1061. }
  1062. {
  1063. pqr();
  1064. }
  1065. Output
  1066. Hello Interfaces
  1067. In xyz
  1068. In pqr

  1069. Program14


  1070. : ,
  1071. {
  1072. Main()
  1073. {
  1074. System..WriteLine("Hello Interfaces");
  1075. ref = ();
  1076. ref = ref;
  1077. ref.xyz();
  1078. ref = ref;
  1079. ref.xyz();
  1080. }
  1081. .xyz()
  1082. {
  1083. System..WriteLine("In .xyz");
  1084. }
  1085. .xyz()
  1086. {
  1087. System..WriteLine("In .xyz");
  1088. }
  1089. }
  1090. {
  1091. xyz();
  1092. }
  1093. {
  1094. xyz();
  1095. }
  1096. Output
  1097. a.cs(13,15): error CS0106: The modifier 'public' not valid thitem
  1098. a.cs(18,15): error CS0106: The modifier 'public' not valid thitem

  1099. Program15


  1100. : ,
  1101. {
  1102. Main()
  1103. {
  1104. System..WriteLine("Hello Interfaces");
  1105. ref = ();
  1106. ref = ref;
  1107. ref.xyz();
  1108. ref = ref;
  1109. ref.xyz();
  1110. }
  1111. .xyz()
  1112. {
  1113. System..WriteLine("In .xyz");
  1114. }
  1115. .xyz()
  1116. {
  1117. System..WriteLine("In .xyz");
  1118. }
  1119. }
  1120. {
  1121. xyz();
  1122. }
  1123. {
  1124. xyz();
  1125. }
  1126. Output
  1127. Hello Interfaces
  1128. In .xyz
  1129. In .xyz

  1130. Program16


  1131. :
  1132. {
  1133. Main()
  1134. {
  1135. System..WriteLine("Hello Interfaces");
  1136. ref = ();
  1137. ref = ref;
  1138. ref.xyz();
  1139. ref.pqr();
  1140. }
  1141. xyz()
  1142. {
  1143. System..WriteLine("In xyz");
  1144. }
  1145. pqr()
  1146. {
  1147. System..WriteLine("In pqr");
  1148. }
  1149. }
  1150. {
  1151. xyz();
  1152. }
  1153. :
  1154. {
  1155. pqr();
  1156. }
  1157. Output
  1158. Hello Interfaces
  1159. In xyz
  1160. In pqr

  1161. Program17


  1162. :
  1163. {
  1164. Main()
  1165. {
  1166. System..WriteLine("Hello Interfaces");
  1167. ref = ();
  1168. ref = ref;
  1169. ref.xyz();
  1170. ref.pqr();
  1171. }
  1172. .xyz()
  1173. {
  1174. System..WriteLine("In xyz");
  1175. }
  1176. .pqr()
  1177. {
  1178. System..WriteLine("In pqr");
  1179. }
  1180. }
  1181. {
  1182. xyz();
  1183. }
  1184. :
  1185. {
  1186. pqr();
  1187. }
  1188. Output
  1189. P17.cs(12,8): error CS0539: '.xyz' declaration
  1190. not a member of interface
  1191. P17.cs(29,11): (Location of symbol related to previous error)
  1192. P17.cs(1,7): error CS0535: '' does not implement member
  1193. '.xyz()'
  1194. P17.cs(26,8): (Location of symbol related to previous error)

  1195. Program18


  1196. :
  1197. {
  1198. Main()
  1199. {
  1200. System..WriteLine("Hello Interfaces");
  1201. ref = ();
  1202. ref = ref;
  1203. ref.xyz();
  1204. ref.pqr();
  1205. }
  1206. .xyz()
  1207. {
  1208. System..WriteLine("In xyz");
  1209. }
  1210. .pqr()
  1211. {
  1212. System..WriteLine("In pqr");
  1213. }
  1214. }
  1215. {
  1216. xyz();
  1217. }
  1218. :
  1219. {
  1220. pqr();
  1221. }
  1222. Output
  1223. Hello Interfaces
  1224. In xyz
  1225. In pqr

  1226. Program19


  1227. :
  1228. {
  1229. Main()
  1230. {
  1231. System..WriteLine("Hello Interfaces");
  1232. ref = ();
  1233. ref.xyz();
  1234. ref.pqr();
  1235. }
  1236. .xyz()
  1237. {
  1238. System..WriteLine("In xyz");
  1239. }
  1240. .pqr()
  1241. {
  1242. System..WriteLine("In pqr");
  1243. }
  1244. }
  1245. {
  1246. xyz();
  1247. }
  1248. :
  1249. {
  1250. pqr();
  1251. }
  1252. Output
  1253. P19.cs(7,5): error CS0117: '' does not contaa inition 'xyz'
  1254. P19.cs(8,5): error CS0117: '' does not contaa inition 'pqr'
  1255. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  1256. 21.Difference between Abstract Class and Interface


  1257. Feature
    Interface
    Abstract Class
    Multiple inheritance
    A class may inherit several interfaces.
    A class may inherit only one abstract class.
    Default implementation
    An interface cannot provide any code, just the signature.
    An abstract class can provide complete, default code and/or just the details that have to be overridden.
    Access Modfiers
    An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public.
    An abstract class can contain access modifiers for the subs, functions, properties.
    Core VS Peripheral
    Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
    An abstract class defines the core identity of a class and there it is used for objects of the same type.
    Homogeneity
    If various implementations only share method signatures then it is better to use Interfaces.
    If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
    Speed
    Requires more time to find the actual method in the corresponding classes.
    Fast.
    Adding functionality (Versioning)
    If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
    If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
    Fields and Constants
    No fields can be defined in interfaces.
    An abstract class can have fields and constrants defined.

  1258. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  1259. 22.Where to use Abstract Class and Where to use Interface?


  1260. Interface


  1261. –> If your child classes should all implement a certain group of methods/functionalities but each of the child classes is free to provide its own implementation then use interfaces.
  1262. For e.g. if you are implementing a class hierarchy for vehicles implement an interface called Vehicle which has properties like Colour MaxSpeed etc. and methods like Drive(). All child classes like Car Scooter AirPlane SolarCar etc. should derive from this base interface but provide a seperate implementation of the methods and properties exposed by Vehicle.
  1263. –> If you want your child classes to implement multiple unrelated functionalities in short multiple inheritance use interfaces.
  1264. For e.g. if you are implementing a class called SpaceShip that has to have functionalities from a Vehicle as well as that from a UFO then make both Vehicle and UFO as interfaces and then create a class SpaceShip that implements both Vehicle and UFO .

  1265. Abstract Classes


  1266. –> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

  1267. For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.
  1268. –> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
  1269. For e.g. a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

  1270. Use an abstract class


  1271. -When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.) -Use an abstract class to define a common base class for a family of types. -Use an abstract class to provide default behavior. -Subclass only a base class in a hierarchy to which the class logically belongs.

  1272. Use an interface


  1273. -When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility. -Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors. -Use an interface to design a polymorphic hierarchy for value types. -Use an interface when an immutable contract is really intended. -A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.

  1274. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  1275. 23.Static Class and Static Class Members:


  1276. 1.Static Class


  1277. The following list provides the main features of a static class:
  1278. •Contains only static members.
  1279. •Cannot be instantiated.
  1280. •Is sealed.
  1281. •Cannot contain Instance Constructors.
  1282. Note:


  1283. To create a non-static class that allows only one instance of itself to be created, Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor.
  1284. Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can contain a static constructor.

  1285. 2.Static Member


  1286. A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter. Static methods can be overloaded but not overridden. Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName. MemberName notation that is used for static fields. No object instance is required. C# does not support static local variables (variables that are declared in method scope).
  1287. Note:
  1288. If your class contains static fields, provide a static constructor that initializes them when the class is loaded.

  1289. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  1290. 24.Aggregation, Association and Composition:


  1291. 1.Association


  1292. It represents a relationship between two or more objects where all objects have their own lifecycle and there is no owner. The name of an association specifies the nature of relationship between objects. This is represented by a solid line.

  1293. Let’s take an example of relationship between Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers. But there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.

  1294. 2.Aggregation


  1295. It is a specialized form of Association where all object have their own lifecycle but there is ownership. This represents “whole-part or a-part-of” relationship. This is represented by a hollow diamond followed by a line.

  1296. Let’s take an example of relationship between Department and Teacher. A Teacher may belongs to multiple departments. Hence Teacher is a part of multiple departments. But if we delete a Department, Teacher Object will not destroy.

  1297. 3.Composition


  1298. It is a specialized form of Aggregation. It is a strong type of Aggregation. In this relationship child objects does not have their lifecycle without Parent object. If a parent object is deleted, all its child objects will also be deleted. This represents “death” relationship. This is represented by a solid diamond followed by a line.

  1299. Let’s take an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room cannot belongs to two different house if we delete the house room will automatically delete.

  1300. Let’s take another example of relationship between Questions and options. Single questions can have multiple options and option cannot belong to multiple questions. If we delete questions options will be automatically deleted.

  1301. 1 (oops)
    2 (class)
    3 (Class & Struct Diff..)
    4 (object)
    5 (Abstraction)
    6 (Encapsulation)
    7 (Encaps & Abst Diff..)
    8 (Access Specifiers)
    9 (specifiers in proper..)
    10 (Object And Instance)
    11 (pointers in C#)
    12 (Inheritance)
    13 (Why multi inheri...)
    14 (Method Hiding)
    15 (Polymorphism)
    16 (Cohesion&Coupling)
    17 (Coupling..)
    18 (Constru & Dest..)
    19 (Abst Class&method)
    20(Interface)
    21(Abst. Class & Int)
    22(Use of abst and Int)
    23(Static Class & Mem)
    24(Aggregation,Asso...)
    25(SOLID Principles)

  1302. 25.SOLID Principles


  1303. SOLID is an acronym and stands for 5 important object oriented principles.
  1304. 1.Single Responsibility Principle
  1305. 2.Open Closed Principle
  1306. 3.Liskov Substitution Principle
  1307. 4.Interface Segregation Principle
  1308. 5.Dependency Inversion Principle

  1309. 1.Single Responsibility Principle:

  1310. SRP states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. There should only be a single reason for making the change to a class.
  1311. It means that a class should not be loaded with multiple responsibilities and a single responsibility should not be scattered across multiple classes and mixed with other responsibilities. The reason is that the more changes requested in the future, the more changes the class needs to undergo.
  1312. Below is a code violating the SRP. In the sample code, SRP is violated by mixing the OpenGate and CloseGate responsibility with the core vehicle service functionality.

  1313. {
  1314. OpenGate()
  1315. {
  1316. //Open the gate the time later than 9 AM
  1317. }
  1318. DoService(Vehicle vehicle)
  1319. {
  1320. //Check service station opened and then
  1321. //complete the vehicle service
  1322. }
  1323. CloseGate()
  1324. {
  1325. //Close the gate the time hcrossed 6PM
  1326. }
  1327. }

  1328. The re-factored code sample is as follows. A new interface is created and the gate related utility methods are moved to a different class called ServiceStationUtility.

  1329. {
  1330. _gateUtility;
  1331. ( gateUtility)
  1332. {
  1333. this._gateUtility = gateUtility;
  1334. }
  1335. OpenForService()
  1336. {
  1337. _gateUtility.OpenGate();
  1338. }
  1339. DoService()
  1340. {
  1341. //Check service station opened and then
  1342. //complete the vehicle service
  1343. }
  1344. CloseForDay()
  1345. {
  1346. _gateUtility.CloseGate();
  1347. }
  1348. }
  1349. Utility :
  1350. {
  1351. OpenGate()
  1352. {
  1353. //Open the shop the time later than 9 AM
  1354. }
  1355. CloseGate()
  1356. {
  1357. //Close the shop the time hcrossed 6PM
  1358. }
  1359. }
  1360. {
  1361. OpenGate();
  1362. CloseGate();
  1363. }

  1364. 2.Open Closed Principle (OCP):

  1365. OCP states that software application source codes should be open for extension but should be closed for modification.
  1366. Sometime modification on a code can create a problem if two or more client is accessing the same code. It is better to give extension for creating new method.

  1367. 3.Liskov Substitution Principle (LSP)

  1368. LSP states that the derived classes should be perfectly substitutable for their base classes. If class D is derived from A then D should be substitutable for A.

  1369. Identify Problem in Programming


  1370. EXAMPLE: Normally when we talk about geometric shapes, we call a rectangle a base class for square. Let’s take a look at code snippet.

  1371. {
  1372. }
  1373. }
  1374. }
  1375. :
  1376. {
  1377. //codes specific to
  1378. //square will be added
  1379. }

  1380. One can say,
  1381. Rectangle o = new Rectangle();
  1382. o.Width = 5;
  1383. o.Height = 6;
  1384. Perfect but as per LSP we should be able to replace Rectangle with square. Let’s try to do so.
  1385. Rectangle o = new Square();
  1386. o.Width = 5;
  1387. o.Height = 6;
  1388. What is the matter? Square cannot have different width and height.
  1389. What is the matter? Square cannot have different width and height.
  1390. Why don’t we make width and height virtual in Rectangle, and override them in Square?
  1391. Code snippet

  1392. :
  1393. {
  1394. Width
  1395. {
  1396. {
  1397. base.Width;
  1398. }
  1399. {
  1400. base.Height = value;
  1401. base.Width = value;
  1402. }
  1403. }
  1404. Height
  1405. {
  1406. {
  1407. base.Height;
  1408. }
  1409. {
  1410. base.Height = value;
  1411. base.Width = value;
  1412. }
  1413. }
  1414. }
  1415. We can’t because doing so we are violating LSP, as we are changing the behavior of Width and Height properties in derived class (for Rectangle height and width cannot be equal, if they are equal it’s cannot be Rectangle).
  1416. (It will not be a kind of replacement).

  1417. Solution which will not violate LSP


  1418. There should be an abstract class Shape which looks like:

  1419. :
  1420. {
  1421. Width { }
  1422. Height { }
  1423. }

  1424. Now there will be two concrete classes independent of each other, one rectangle and one square, both of which will be derived from Shape.
  1425. Now the developer can say:
  1426. Shape o = new Rectangle();
  1427. o.Width = 5;
  1428. o.Height = 6;
  1429. Shape o = new Square();
  1430. o.Width = 5; //both height and width become 5
  1431. o.Height = 6; //both height and width become 6

  1432. 4.Interface Segregation principle (ISP)


  1433. ISP states that no clients should be forced to implement methods which it does not use and the contracts should be broken down to thin ones.

  1434. Say for example when a thick interface is defined declaring a wide responsibility of members then there will be opportunities where some clients may have to implement members, which they don’t even use. In the below mentioned example ISP is violated where ProcessCreditCard method is not required by InpersonOrder class but is forced to implement.
  1435. {
  1436. Purchase();
  1437. ProcessCreditCard();
  1438. }
  1439. :
  1440. {
  1441. Purchase()
  1442. {
  1443. //Do purchase
  1444. }
  1445. ProcessCreditCard()
  1446. {
  1447. //process through credit card
  1448. }
  1449. }
  1450. :
  1451. {
  1452. Purchase()
  1453. {
  1454. //Do purchase
  1455. }
  1456. ProcessCreditCard()
  1457. {
  1458. //Not required inperson purchase
  1459. ();
  1460. }
  1461. }
  1462. Now let us fix the violation by breaking down the IOrder interface.
  1463. {
  1464. Purchase();
  1465. }
  1466. I
  1467. {
  1468. ProcessCreditCard();
  1469. }
  1470. : , I
  1471. {
  1472. Purchase()
  1473. {
  1474. //Do purchase
  1475. }
  1476. ProcessCreditCard()
  1477. {
  1478. //process through credit card
  1479. }
  1480. }
  1481. :
  1482. {
  1483. Purchase()
  1484. {
  1485. //Do purchase
  1486. }
  1487. }

  1488. 5. Dependency Inversion Principle (DIP).


  1489. DIP states that the higher level modules should be coupled with the lower level modules with complete abstraction.

  1490. Dependency Injection Principle states that there should be more abstraction between the higher level module and the lower level module. It is required to have loose coupling so that any change in the low level modules will not affect or there will be minimal impact at the higher level module. The ideal scenario would be when you write components for other applications to consume.

  1491. Real World Comparison


  1492. Let’s talk about our desktop computers. Different parts such as RAM, a hard disk, and CD-ROM (etc.) are loosely connected to the motherboard. That means that, if, in future in any part stops working it can easily be replaced with a new one. Just imagine a situation where all parts were tightly coupled to each other, which means it would not be possible to remove any part from the motherboard. Then in that case if the RAM stops working we have to buy new motherboard which is going to be very expensive.