Encapsulation: Encapsulation is a process of binding the data
members and member functions into a single unit.
Example for encapsulation is class. A class
can contain data structures and methods.
Consider the following class
public class
Aperture
{
public Aperture ()
{
}
protected double
height;
protected double
width;
protected double
thickness;
public double
get volume()
{
Double volume=height * width *
thickness;
if (volume<0 span="">0>
return 0;
return volume;
}
}
In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier
Abstraction: Abstraction is a process of hiding the
implementation details and displaying the essential features.
Example1: A Laptop consists of many things such as
processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web
camera, usb ports, battery, speakers etc. To use it, you don't need to
know how internally LCD screens, keyboard, web camera, battery, wireless
antenna, speaker’s works. You just need to know how to operate the
laptop by switching it on. Think about if you would have to call to the
engineer who knows all internal details of the laptop before operating it.
This would have highly expensive as well as not easy to use everywhere by
everyone.
So here the Laptop is an object
that is designed to hide its complexity.
How to abstract: - By using Access
Specifiers
.Net
has five access Specifiers
Public - Accessible outside the class through object
reference.
Private - Accessible inside the class only through
member functions.
Protected -- Just like private but Accessible in
derived classes also through member
functions.
Internal -- Visible inside the assembly. Accessible
through objects.
Protected Internal -- Visible inside the assembly through
objects and in derived classes outside the assembly through member functions.
In object-oriented software,
complexity is managed by using abstraction.
Abstraction is a process that involves identifying the
critical behavior of an object and eliminating irrelevant and complex details.
Inheritance:Inheritance is a process of deriving the new
class from already existing class
C#
is a complete object oriented programming language. Inheritance is one of the
primary concepts of object-oriented programming. It allows you to reuse
existing code. Through effective use of inheritance, you can save lot of time
in your programming and also reduce errors, which in turn will increase the
quality of work and productivity. A simple example to understand inheritance in
C#.
Using System;
Public class BaseClass
{
Public
BaseClass ()
{
Console.WriteLine ("Base
Class Constructor executed");
}
Public
void Write ()
{
Console.WriteLine ("Write
method in Base Class executed");
}
}
Public class ChildClass: BaseClass
{
Public
ChildClass ()
{
Console.WriteLine("Child
Class Constructor executed");
}
Public
static void
Main ()
{
ChildClass CC = new
ChildClass ();
CC.Write
();
}
}
In the Main () method in ChildClass we
create an instance of childclass. Then we call the write () method. If you
observe the ChildClass does not have a write() method in it. This write ()
method has been inherited from the parent BaseClass.
The output of the above program is
Output:
Output:
Base Class Constructor executed
Child Class Constructor executed
Write method in Base Class executed
Child Class Constructor executed
Write method in Base Class executed
this output proves that when we create
an instance of a child class, the base class constructor will automatically be
called before the child class constructor. So in general Base classes are
automatically instantiated before derived classes.
In C# the syntax for specifying
BaseClass and ChildClass relationship is shown below. The base class is
specified by adding a colon, ":", after the derived class identifier
and then specifying the base class name.
Syntax: class ChildClassName: BaseClass
{
//Body
}
{
//Body
}
C# supports single class inheritance
only. What this means is, your class can inherit from only one base class at a
time. In the code snippet below, class C is trying to inherit from Class A and
B at the same time. This is not allowed in C#. This will lead to a compile
time
error: Class 'C' cannot have
multiple base classes: 'A' and 'B'.
public class A
{
}
public class B
{
}
public class C : A, B
{
}
In C# Multi-Level inheritance is
possible. Code snippet below demonstrates mlti-level inheritance. Class B is
derived from Class A. Class C is derived from Class B. So class C, will have
access to all members present in both Class A and Class B. As a result of
multi-level inheritance Class has access to A_Method(),B_Method() and
C_Method().
Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces.
Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces.
Using System;
Public class A
{
Public
void A_Method ()
{
Console.WriteLine ("Class
A Method Called");
}
}
Public class B: A
{
Public
void B_Method ()
{
Console.WriteLine ("Class
A Method Called");
}
}
Public class C: B
{
Public
void C_Method ()
{
Console.WriteLine ("Class
A Method Called");
}
Public
static void
Main ()
{
C C1 = new C ();
C1.A_Method ();
C1.B_Method ();
C1.C_Method ();
}
}
When you derive a class from a base
class, the derived class will inherit all members of the base class except
constructors. In the code snippet below class B will inherit both M1 and M2
from Class A, but you cannot access M2 because of the private access modifier.
Class members declared with a private access modifier can be accessed only with
in the class.
Common Interview Question: Are private class members inherited to the derived class?
Ans: Yes, the private members are also inherited
in the derived class but we will not be able to access them. Trying to access a
private base class member in the derived class will report a compile time
error.
Using System;
Public class A
{
Public void M1 ()
{
}
Private void M2 ()
{
}
}
Public class B: A
{
Public static void Main ()
{
B
B1 = new B
();
B1.M1 ();
//Error, Cannot access private
member M2
//B1.M2 ();
}
}
What is wrong with multiple inheritance?
The main problem with multiple inheritance is that there can be times when the results of using multiple inheritance will be uncertain. The best example of this is the classic problem known as the diamond problem where a class inherits from 2 different classes, but those 2 different classes inherit from the same class, like in the graphic below (where class D derives from both classes B and C, and classes B and C both derive from class A:And here is what the code for that example would look like:
class A {
protected:
bool testing;
};
class B: public A { };
class C: public A { };
class D: public B, public C {
public:
void setTesting ( bool xTesting) {
testing = xTesting; // this is uncertain
}
};
In
the code above we have the testing data member which is defined by class
A. But, the problem is that class D derives from both classes B and C, which
both derive from class A. This means that there are essentially 2 copies of the
testing flag that are available because there are 2 instances of A in
D’s class hierarchy. So, this creates a problem because which copy of the testing
flag will be set? And the compiler will give an error and say that the reference
to testing in class D is ambiguous. But, there are some fixes to this problem. One fix is to make it very clear which classe’s version of testing is going to be set:
B :: testing = xTesting; // use B's version of testing
The
other fix for this problem is to declare B and C as virtual base classes. This
allows only one copy of A to be created for class D, and that clears up any
ambiguities. Different languages actually have different expectations for how multiple inheritance works. For example, how conflicts are resolved and whether duplicate bases are merged or redundant. Before microsoft can implement multiple inheritance in the CLR, microsoft have to do a survey of all the languages, figure out the common concepts, and decide how to express them in a language-neutral manner. microsoft could also have to decide whether multiple inheritance belongs in the CLS and what this would mean for languages that don't want this concept (presumably VB.NET, for example).
Polymorphism: Polymorphism
means many forms (ability to take more than one form).
In polymorphism
we will declare methods with same name and different parameters in same class
or methods with same name and same parameters in different classes. Polymorphism
has ability to provide different implementation of methods that are implemented
with same name.
In Polymorphism we have 2 different
types those are
- Compile
Time Polymorphism (Called as Early
Binding or Overloading or static binding)
- Run
Time Polymorphism (Called as Late
Binding or Overriding or dynamic binding)
Compile Time
Polymorphism or Early Binding
In
Compile time polymorphism, the
decision is made at compile time. It
means we will declare methods with same name but different signatures because
of this we will perform different tasks with same method name. This compile
time polymorphism also called as early binding or method /operator /constructor
overloading.
Overloading is mainly three types i.e.
1.
Method Overloading: Method Overloading or compile time
polymorphism means same method names with different signatures (different
parameters)
2.
Operator Overloading
3.
Constructor overloading
Example:
public class
Class1
{
public void
NumbersAdd(int a, int
b)
{
Console.WriteLine(a + b);
}
public void
NumbersAdd(int a, int
b, int c)
{
Console.WriteLine(a + b + c);
}
}
In
above class we have two methods with same name but having different input
parameters this is called method overloading or compile time polymorphism or
early binding.
Run Time
Polymorphism or Late Binding
Run time polymorphism also called as late
binding or method overriding or dynamic polymorphism. Run
time polymorphism or method overriding means same method names with same
signatures.
In this run time polymorphism or
method overriding we can override a method in base class by creating similar
function in derived class this can be achieved by using inheritance principle
and using “virtual & override” keywords.
In
base class if we declare methods with virtual keyword then only we can
override those methods in derived class using override keyword
Example:
//Base
Class
public class
Bclass
{
public virtual
void Sample1()
{
Console.WriteLine("Base Class");
}
}
//
Derived Class
public class
DClass : Bclass
{
public override
void Sample1()
{
Console.WriteLine("Derived Class");
}
}
// Using
base and derived class
class Program
{
static void
Main(string[] args)
{
// calling the
overriden method
DClass objDc = new DClass();
objDc.Sample1();
// calling the
base class method
Bclass objBc = new DClass();
objBc.Sample1();
}
}
Virtual
Method: Virtual method is a method whose behavior can be overridden in
derived class. Virtual method allows declare a method in base class that can be
redefined in each derived class.
- By default, methods are non-virtual. You cannot override a non-virtual method.
- You cannot use the virtual modifier with the static, abstract, private or override modifiers.
- Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.
- A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
·
If a Virtual function derived in derived class without mentioning
“override” keyword then it will work as in case of new keyword.