Showing posts with label OOPS. Show all posts
Showing posts with label OOPS. Show all posts

In .NET how to achieve Multiple Inheritance using Interface

Diamond Problem :

The Diamond problem is related to object oriented languages that allow multiple inheritance.As we know C# does not support multiple inheritance of classes, but it does support multiple inheritance through interfaces. Therefore, the same ambiguity may arise unless explicit interface implementation is used. Going explicitly, we can have different implementations to the same method. The problem is solved.




namespace
MulipleInheritance
{


public interface IntBC
{
void Display();
}


public interface IntA : IntBC
{
new void Display();
}


public interface IntB : IntBC
{
new void Display();
}


// C class implements the IntA and IntB interfaces
public class C : IntA, IntB
{
// explicitly implement the Display() method of the IntA interface
void IntA.Display()
{
Console.WriteLine("IntA implementation of Display()");
}
// implement the Display() method of the IntB interface
public void Display()
{
Console.WriteLine("IntB implementation of Display()");
}
}


public class
MainClass
{
public static void Main()
{
C ObjC = new C();
Console.WriteLine("Calling ObjC.Display()");
ObjC.Display();
// cast ObjC to IntB
IntA RefIntA = ObjC as IntA;
Console.WriteLine("Calling RefIntA.Display()");
RefIntA.Display();
// cast ObjC to IntA
IntB RefIntB = ObjC as IntB;
Console.WriteLine("Calling RefIntB.Display()");
RefIntB.Display();
}
}


}

Output :

Calling ObjC.Display()
IntB implementation of Display()
Calling RefIntA.Display()
IntA implementation of Display()
Calling RefIntB.Display()
IntB implementation of Display()

In Class C, first Display() method is explicitly implemented for IntA Interface. Explicit implementation is not needed for the second Display() method, because previous statement already did that and the method implementation is automatically assumed to IntB interface. In order to call explicit implementation method casting is required.



Why Multiple inheritance is not supported in .NET

Multiple Inheritance:

Multiple inheritance may allow you to write compact code but it has some program difficulties like "diamond problem" for example

Diamond problem :



class
BaseClass
{
public abstract void Display();
}

class A : BaseClass
{
public override void Display()
{
Debug.WriteLine("First Child A");
}
}

class B : BaseClass
{
public override void Display()
{
Debug.WriteLine("Second Child B");
}
}

//Now Suppose that c# support multiple inheritance

class C : A, B
{
}

public class MainClass
{
public static void main()
{
C ObjC =new C();
ObjC.Display();
}
}

By excuting ObjC.Display() method Diamond problem is generated. It means which Display method going to executed.

Static Constructor in C#


Static Constructors:


It is a Special type of constructor. It gets called before the creation of first object of class(Probably at the time of loading an assembly).


Rules to create a static constructor:

  • There is no access modifier require to define a static constructor.
  • There may be only one static constructor in a class.
  • The static constructor may not have any parameters.
  • This constructor may only access the static members of the class

Static constructor is used to initialize static data members as soon as the class is referenced first time.You can also initialize static data members where we declare them in the code.

Like this :
public static int id = 10;

But value of one static member may depend upon the value of another static member .In order to handle such cases you need some manipulation before static members going to be initialize.
This you can achieve through static constructors.


namespace StaticConstructor
{


class MainClass
{
static void Main(string[] args)
{
Console.WriteLine("Id value is " + ClsStaticConstructor.id);
}
}


class
ClsStaticConstructor
{
public static int id;

static ClsStaticConstructor()
{
if (Sample.Value == 10)
id = 20;
else
id = 40;
}
}


public class
Sample
{
public static int Value = 10;
}


}


Output
:

Id value is : 20


Difference between Abstraction and Encapsulation

Abstraction:

It is virtual class design.
Representation of data that how we represent it.
Before actually defining class developer will think about about the properties, methods and events will be there in class.

Encapsulation:

Hiding of unnecessary data.
At the time of class definition developers will think about which should display to end user and which should not.

Conclusion:
Abstraction is collection of data and Encapsulation is exposure of data in appropriate access specifier.

Encapsulation

When designing a class, it is generally a good practice to only reveal the necessary interfaces needed to interact with the object, and hide the implementation details that are not precisely relevant. This hiding of details is known as encapsulation.

The concept of encapsulation is better enforced with the definitions of interfaces and implementations. An interface is defined by the services of communication between objects. Classes declare some methods and properties as visible to outside objects, and hide the other details. The visible, or public, methods and properties become the interface to the object. Interfaces typically only include methods, since any need to access an attribute should be made available through a public method.

public class ClsEncapsulation
{
int SqrOutput;
public ClsEncapsulation()
{
}
//Visible method
public void AssignNumber(int GivenNumber)
{
CalculateSqluare(GivenNumber);
}
public void Display()
{
Console.WriteLine("Square of given number is " + SqrOutput.ToString());
}
//Hiding Method
private void CalculateSqluare(int GnNumber)
{
SqrOutput = System.Math.Pow(GnNumber,2);
}

}

Assembly Vs Namespace

Assembly:
  • An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). It's a managed dll or exe (built by .NET).Assemblies are Self-Describing. [e.g. metadata,manifest]
  • One assembly can contain several namespaces.
Namespace:
  • A group of managed types (classes, enums, structs, etc). It form the logical boundary for a Group of classes.
  • One namespace can contain types(Objects) from different assemblies.
  • The name of the namespace is not necessarily the name of the assembly.

Basics of .NET Namespace

Namespace are logical grouping of classes and other types such as unions, structures, interfaces and enumerators.

In Microsoft .Net, every program is created with a default namespace. This default namespace is called as global namespace. But the program itself can declare any number of namespaces, each of them with a unique name. The advantage is that every namespace can contain any number of classes, functions, variables and also namespaces etc., whose names are unique only inside the namespace. The members with the same name can be created in some other namespace without any compiler complaints from Microsoft .Net.

If a new project is created in Visual Studio .NET it automatically adds some global namespaces. These namespaces can be different in different projects. But each of them should be placed under the base namespace System.

namespace Books
{
class Authors
{
public void Display()
{
Console.WriteLine("Auther name is Dynamic-Coding");
}
}
This is simple namespace example. We can also build hierarchy of namespace. Here is an example for this.

namespace Books
{
namespace Inventory
{
using System;
class AddInventory
{
public void MyMethod()
{
Console.WriteLine("Adding Inventory via MyMethod!");
}
}
}
}

Let's look how we can use the namespaces in our code

using Books;
class HelloWorld
{
public static void Main()
{
Inventory.AddInventory AddInv = new AddInventory();
AddInv.MyMethod();
}
}

OR

using Books.Inventory;
class HelloWorld
{
public static void Main()
{
AddInventory AddInv = new AddInventory();
AddInv.MyMethod();
}
}

Note:
The namespaces wide opens the doors for 3rd party and project specific custom components and class libraries.

Overriding Vs Hiding/Shadowing

Overriding:
  • An override method provides a new implementation of a member inherited from a base class. The overridden base method must have the same signature as the override method.You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
  • Only a procedure (Function or Sub) or property
  • Overriding the accessibility is not possible(Base and child class having same access specifiers).
  • Overriding element inherited by further derived classes; overridden element still overridden.
Hiding(C#)/Shadowing(VB.NET):
  • When two programming elements share the same name, one of them can hide, or shadow, the other one. In such a situation, the shadowed element is not available for reference.
  • It applied to any declared element type(procedure (Function or Sub) or property and fields).
  • Any accessibility is possible.
  • Shadowing element inherited by further derived classes; shadowed element still hidden.


class BaseClass
{
public int X = 10;
public virtual string overridingMethod()
{
return "BaseClass overridingMethod \n";
}
public string hidingMethod()
{
return "BaseClass hidingMethod \n";
}
public void ParentDisplay()
{
Console.WriteLine("Paerent " + X);
}
}

class DerivedClass : BaseClass
{
public new string X = "Hai";
//Hiding applied even field also(new keyword used for hiding)

public override string overridingMethod()
{
return "DerivedClass overridingMethod \n";
}
internal new string hidingMethod()
//Change of accessibility possible in hiding
{
return "DerivedClass hidingMethod \n";
}
public void childDisplay()
{
Console.WriteLine("Child " + X);
}
}

class MainClass
{
static void Main()
{
BaseClass bc = new BaseClass();
Console.WriteLine("Base class ref assigned to Base class object");
bc.ParentDisplay();
Console.Write(bc.overridingMethod());
Console.Write(bc.hidingMethod());
DerivedClass dc = new DerivedClass();
Console.WriteLine("");
Console.WriteLine("Derived class ref assigned to Derived class object");
dc.ParentDisplay();
dc.childDisplay();
Console.Write(dc.overridingMethod());
Console.Write(dc.hidingMethod());
BaseClass bc2 = new DerivedClass();
Console.WriteLine("");
Console.WriteLine("Base class ref assigned to Derived class object");
bc2.ParentDisplay();
Console.Write(bc2.overridingMethod());
//It will return overrided method(not relavent to it's reference)
Console.Write(bc2.hidingMethod()); //It will return method which is relavent to it's reference
}
}

Output :

Base class ref assigned to Base class object
Parent 10
BaseClass overridingMethod
BaseClass hidingMethod

Derived class ref assigned to Derived class object
Parent 10
Child Hai
DerivedClass overridingMethod
DerivedClass hidingMethod

Base class ref assigned to Derived class object
Parent 10
DerivedClass overridingMethod
BaseClass hidingMethod

Abstract Class Vs Interface

Abstract Class :

We can not make instance of Abstract Class as well as Interface. It cannot be a sealed class. It can contain abstract methods, abstract property as well as other members (just like normal class).

Interface:

Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract. Interface are useful to achieve Multiple inheritence.

abstact class is a abstract view of any realword entity and interface is more abstract one


//Abstract class
public abstract class Calculate
{
public abstract int Result
{
get;
set;
}
public abstract void Summation(int First, int Second);
}


//Interface
public interface ICalculate
{
int Result
{
get;
set;
}
void Summation(int First, int Second);
}


//Abstract class inherited class
public class ClsAbstraction : Calculate
{
private int m_Result;
public override void Summation(int First, int Second)
{
m_Result = First + Second;
}
public override int Result
{
get { return m_Result; }
set { m_Result = value; }
}
}


//Interface implemented class
public class ClsInterface : ICalculate
{
private int m_Result;
public void Summation(int First, int Second)
{
m_Result = First + Second;
}
public int Result
{
get { return m_Result; }
set { m_Result = value; }
}
}


//Main class
public class ClsMain
{
public static void Main()
{
//Using abstarct class
ClsAbstraction objClsAbstarction = new ClsAbstraction();
objClsAbstarction.Summation(4, 5);
Console.WriteLine("Abs class result " + objClsAbstarction.Result);
//Using Interface
ClsInterface ObjClsInterface = new ClsInterface();
ObjClsInterface.Summation(5, 5);
Console.WriteLine("Interface result " + ObjClsInterface.Result);
}
}


Conclusion:

Abstract class having upper-hand in compare to interface. Using interface having only advantage of multiple inheritance.