Вы находитесь на странице: 1из 14

OOPs Concept and Asp.

Net
Definition : Object-oriented programming (OOP) is a programming concept based on the
concept of "objects", which are data structures that contain data, in the form
of fields, often known as attributes; and code, in the form of procedures, often
known as methods.
Area to be cover in OOPs

Class
Object
Encapsulation
Abstraction

Polymorphism
Interface

Virtual Class

Let start with each one

Class
A class is basically a combination of a set of rules on which we will work in a
specific program.
It contains definitions of new data types like fields or variables, operations that
we will perform on data (methods) and access rules for that data.
Example
1. Class Example
2. {
3.
/* fields,
4.
Variables,
5.
Methods,
6.
Properties,
7.
*/
8. }

Object
Objects are defined as an instance of a class. Objects are built on the model defined
by the class. An object can be created in memory using the "new" keyword.
In C# objects are reference types and other data type variables are value types. In
C# objects are stored in the heap while other value types are stored in the stack.
Example

Example exmplObject = new Example();

Inheritance

Inheritance is relevant due to the concept of Code Reusability. Inheritance is a


feature by which a class acquires attributes of another class.
The class that provides its attributes is known as the base class and the class that
accepts those attributes is known as a derived class.
It allows programmers to enhance their class without reconstructing it.
Example
9. public class ParentClass
10.
{
11.
public ParentClass()
12.
{
13.
Console.WriteLine("Parent Constructor.");
14.
}
15.
16.
public void print()
17.
{
18.
Console.WriteLine("I'm a Parent Class.");
19.
}
20.
}
21.
22.
public class ChildClass : ParentClass
23.
{
24.
public ChildClass()
25.
{
26.
Console.WriteLine("Child Constructor.");
27.
}
28.
29.
public static void Main()
30.
{
31.
ChildClass child = new ChildClass();
32.
33.
child.print();
34.
}
35.
}

Encapsulation
Encapsulation is defined as hiding irrelevant data from the user. A class may contain
much information that is not useful for an outside class or interface. The idea behind
this concept is Dont tell me how you do it. Just do it.
So classes use encapsulation to hide its members that are not relevant for an outside
class or interface. Encapsulation can be done using access specifiers.

Encapsulation means hiding the internal details of an object, i.e., how an object
does something.
Encapsulation prevents clients from seeing its inside view, where the behaviour of
the abstraction is implemented.
Encapsulation is a technique used to protect the information in an object from the
other object.
Hide the data for security such as making the variables as private, and expose the
property to access theprivate data which would be public.
So, when you access the property, you can validate the data and set it.

Example
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.

class Demo
{
private int _mark;
public int Mark
{
get { return _mark; }
set { if (_mark > 0) _mark = value; else _mark = 0; }
}
}

Abstraction
Abstraction is "To represent the essential feature without representing the
background details."
Abstraction lets you focus on what the object does instead of how it does it.
Abstraction provides you a generalized view of your classes or object by providing
relevant information.
Abstraction is the process of hiding the working style of an object, and showing the
information of an object in an understandable manner.

Example
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.

using System;
namespace ProgramCall
{
//Abstract class
abstract class Shape1
{
protected float R, L, B;
//Abstract methods can have only declarations
public abstract float Area();
public abstract float Circumference();
}
class Rectangle1 : Shape1
{
public void GetLB()
{
Console.Write("Enter

Length

");

L = float.Parse(Console.ReadLine());
Console.Write("Enter Breadth : ");
B = float.Parse(Console.ReadLine());
}
public override float Area()
{

80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.

return L * B;
}
public override float Circumference()
{
return 2 * (L + B);
}
}
class Circle1 : Shape1
{
public void GetRadius()
{
Console.Write("Enter Radius : ");
R = float.Parse(Console.ReadLine());
}
public override float Area()
{
return 3.14F * R * R;
}
public override float Circumference()
{
return 2 * 3.14F * R;
}
}
class MainClass
{
public static void Calculate(Shape1 S)
{
Console.WriteLine("Area : {0}", S.Area());
Console.WriteLine("Circumference : {0}", S.Circumference());
}
static void Main()
{
Rectangle1 R = new Rectangle1();
R.GetLB();
Calculate(R);
Console.WriteLine();
Circle1 C = new Circle1();
C.GetRadius();
Calculate(C);
Console.Read();
}
}
}

Polymorphism
Polymorphism means one name many forms.
One function behaves in different forms.

In other words, "Many forms of a single object is called Polymorphism."


Real World Example of Polymorphism
Example 1
A Teacher behaves with his student.
A Teacher behaves with his/her seniors.
Here teacher is an object but attitude is different in different situations.
Example 2
Person behaves like a SON in the house, at the same time that person behaves
like an EMPLOYEE in office.
Example 3
Your mobile phone, one name but many forms:

As
As
As
As

phone
camera
mp3 player
radio

Interface
An interface looks like a class, but has no implementation. The only thing it
contains is declarations of events, indexers, methods and/or properties.
The reason interfaces only provide declarations is because they are inherited by
classes that must provide an implementation for each interface member declared.
Why to use Interface: Inheritance allows creating classes that are derived from other
classes, so that they automatically include some of its "parent's" members, plus its
own. The following are types of inheritances.
Best Example of interface is:

ODDEVEN.cs
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.

using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace InterFaceDemo
{
interface IOne
{
void ONE();//Pure Abstract Method Signature
}
interface ITwo
{
void TWO();
}
interface IThree:IOne

154.
{
155.
void THREE();
156.
}
157.
interface IFour
158.
{
159.
void FOUR();
160.
}
161.
interface IFive:IThree
162.
{
163.
void FIVE();
164.
}
165.
interface IEVEN:ITwo,IFour
166.
{
167.
168.
}
169.
class ODDEVEN:IEVEN,IFive//Must Implement all the abstract method, in
Derived class.
170.
{
171.
public void ONE()//Implementation of Abstract Method.
172.
{
173.
Console.WriteLine("This is ONE");
174.
}
175.
public void TWO()
176.
{
177.
Console.WriteLine("This is TWO");
178.
}
179.
public void THREE()
180.
{
181.
Console.WriteLine("This is THERE");
182.
}
183.
public void FOUR()
184.
{
185.
Console.WriteLine("This is FOUR");
186.
}
187.
public void FIVE()
188.
{
189.
Console.WriteLine("This is FIVE");
190.
}
191.
192.
}
193.
}
Program.cs
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.

using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace InterFaceDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is ODD");
IFive obj1 = new ODDEVEN();
obj1.ONE();
obj1.THREE();
obj1.FIVE();
Console.WriteLine("\n\nThis is EVEN");
IEVEN obj2 = new ODDEVEN();
obj2.TWO();
obj2.FOUR();

216.
217.
218.
219.
220.
221.

Console.ReadLine();
}
}
}

The following is the output:

Namespace
Namespaces are a way to define the classes and other types of information into one
hierarchical structure.
System is the basic namespace used by every .NET code. If we can explore the System
namespace little bit, we can see it has lot of namespace user the system namespace.
For example, System.Io, System.Net, System.Collections, System.Threading, etc.

Example:
222.
namespace Books
{
class Authors
{
//Do something
}
}
This is simple namespace example. We can also build hierarchy of namespace. Here is an
example for this.
Example:
223.
namespace Books
{
namespace Inventory
{
using System;
class AddInventory
{
public void MyMethod()
{
Console.WriteLine("Adding Inventory via MyMethod!");
}
}
}
}
That's all it takes to create namespace. Let's look how we can use the namespaces in
our code. I'm going to create a standalone program to use the namespaces.

Virtual Class
A virtual method is a method that can be redefined in derived classes. A virtual
method has an implementation in a base class as well as derived the class.
It is used when a method's basic functionality is the same but sometimes more
functionality is needed in the derived class.
A virtual method is created in the base class that can be overridden in the derived
class.
We create a virtual method in the base class using the virtual keyword and that method
is overridden in the derived class using the override keyword.

What is Method Overloading?


Creating a multiple methods in a class with same name but different parameters and
return types is called as method overloading.
Method overloading is the example of Compile time polymorphism which is
compile time.

done at

Method overloading can be achieved by using following things:

By changing the number of parameters used.


By changing the order of parameters.
By using different data types for the parameters.

1. public class Methodoverloading


2.
{
3.
public int add(int a, int b) //two int type Parameters method
4.
{
5.
return a + b;
6.
7.
}
8.
public int add(int a, int b,int c) //three int type Parameters with same meth
od same as above
9.
{
10.
return a + b +c;
11.
12.
}
13.
public float add(float a, float b,float c,float d) //four float ty
pe Parameters with same method same as above two method
14.
15.
16.
17.
18.

{
return a + b + c + d;
}
}

In the above example, there are three methods with same method same but they differ
with number of parameters and type of parameters ,hence this types of methods is
called as method overloading.
FAQ of Method Overloading
QuestionCan method overloading has same numbers of parameters and Name with
different return types?
Answer- No, because conflict is happen in methods while passing the parameters.

What is Method overriding?


Creating the method in a derived class with same name, same parameters and same return
type as in base class is called as method overriding.
Method overriding is the example of run time polymorphism
Some Key Points of Method overriding

Method overriding is only possible in derived class not within the same class
where the method is declared.
Only those methods are overrides in the derived class which is declared in the base
class with the help of virtual keyword or abstract keyword.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.

public class Account


{
public virtual int balance()
{
return 10;
}
}
public class Amount:Account
{
public override int balance()
{
return 500;
}
}

Output of the above Program is

10 and 500

In the above small program there are two classes Account and Amount and both the
classes contain same method Name that balance() in which Account class method returns
10 and Amount class returns 500 at run time because Account class method is
overridden in a class Amount.
The Method overriding is very useful when we wants to return different output of same
method in different class according to the need.
Let us consider the example I wants to provide the discount on particular product
according to the Customer category that A,B,C in this scenario suppose A,B,C are the
classes and Discount is the class which contains virtual CustDiscount () method ,then
i simply override it on class A,B,C instead of writing three different methods for
each class.
I hope you understand about the Method overriding and Method overloading, In my next
article we will see the real time examples of Method overriding and Method
overloading.

Garbage Collection in .Net


The garbage collector in .Net takes care of bulk of the memory management
responsibility, freeing up the developer to focus on core issues. The garbage
collector is optimized to perform the memory free-up at the best time based upon the
allocations being made. Java developers have enjoyed the benefits of Garbage
collection. VB developers are also used to a certain amount of flexibility in these
terms and .Net provides full-fledged memory management capabilities for managed
resources.

Release Unmanaged Resources - Runtime Garbage Collector


The .Net developer is still responsible for tracking and managing "unmanaged"
resources. An example of unmanaged resources is Operating System resources such as
file, window or network connection. The framework can track when the unmanaged
resource needs to be terminated, but it does not have information on how to terminate
the resource and free up the memory. For clean-up of these resources, the framework
provides destructors in C# and Managed Extensions for C++ and the Finalize method for
other programming languages. The developer must override the Finalize method (or the
destructor for C#, Managed Extensions) to release and terminate the unmanaged
resources.
When the Garbage collector executes, it does not delete objects which have the
Finalize method overridden. Instead, it adds them to a separate list called the
Finalization queue. A special runtime thread becomes active and calls Finalize methods
for these objects and then removes them from this list. When the garbage collector
runs for the next time, these objects are terminated and the memory is released.
Programmatically Invoking the Garbage Collector
In applications with significant memory requirements, you can force garbage collection
by invoking the GC.Collect method from the program. This is not recommended and should
be used only in extreme cases.
System.GC class
The System.GC class provides methods that control the system garbage collector. Use
methods from this class in your application with extreme caution.

Constructor
Constructors are special methods called when a class is instantiated.

Constructor will not return anything.


Constructor name is same as class name.
By default C# will create default constructor internally.
Constructor with no arguments and no body is called default constructor.
Constructor with arguments is called parameterized constructor.
Constructor by default public.
We can create private constructors.
A method with same name as class name is called constructor there is no separate
keyword.

using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace BRK.ConstructorExample
{
class Welcome
{
// Default constructor
public Welcome()
{
Console.WriteLine("Welcome message from Default Constructor...");
}
// Parametarized constructor
public Welcome (string name)
{
Console.WriteLine("\n\n This message from parametarized constructor");

Console.WriteLine("Welcome to Constructor sample, by {0}", name);


}
}
class Program
{
static void Main(string[] args)
{
// Creating object for Welcome class
// This will called default constructor
Welcome obj = new Welcome();
// Creating object for welcome class by passing parameter
// This will called parametarized constructor which matches
Welcome pObj = new Welcome("Ramakrishna Basgalla");
Console.Read();
}
}
}
Output:

Private Constructor
As I mentioned above we can create private constructors, but we have limitation in
using that. The following program shows how to create and use a private constructor.
Sample Program:
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace BRK.PrivateConstructorSample
{
class Welcome
{
// Default private constructor
private Welcome()
{
Console.WriteLine("Welcome message from Default Private Constructor...");
Console.WriteLine("Created by Ramakrishna Basagalla (-:");
}
static void Main(string[] args)
{
// Creating object for Welcome class
// This will called default private constructor
Welcome obj = new Welcome();
Console.Read();
}
}

}
Output:

To use a private constructor we should have main function in the same class, generally
we will define constructors in different classes so defining private constructors is
not that much useful.
Static Constructor
A static constructor has the same name as the class name but preceded with the static
keyword; it will be called at the time of class load.

No access specifier for


Static constructor will
Static constructor will
Static constructor will
Static constructor will
constructor.

static constructor.
not return anything.
accept only static members.
call at the time of class loading.
not allow overloading, so there is no parameterized static

Sample Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BRK.ConstructorExample
{
class Welcome
{
public static string Name = "Ramakrishna Basagalla";
// Static Constructor
static Welcome()
{
Console.WriteLine("Welcome message from static Constructor...");
Console.WriteLine("{0} name is coming from static member",Name);
}
// Parametarized constructor
public Welcome(string name)
{
Console.WriteLine("\n\nThis message from parametarized constructor");
Console.WriteLine("Welcome to Constructor sample, by {0}", name);
}
}
class Program
{
static void Main(string[] args)
{
// Creating object for welcome class by passing parameter
// This will called parametarized constructor which matches
Welcome pObj = new Welcome("Ramakrishna Basgalla");
Console.Read();
}
}

}
Output:

In the above program we have created parameterized object for Welcome class, here the
static constructor is called at the time of class load after then it's called
corresponding parameterized constructor.
Destructors
.Net will clean up the un-used objects by using garbage collection process. It
internally uses the destruction method to clean up the un-used objects. Some times the
programmer needs to do manual cleanup.
Syntax:
~<ClassName>
{}
Sample Program:
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace BRK.ConstructorExample
{
class Welcome
{
// Default constructor
public Welcome()
{
Console.WriteLine("Welcome message from Default Constructor...");
}
// Destructor
~Welcome()
{
Console.WriteLine("Destructor called");
}
}
class Program
{
static void Main(string[] args)
{
// Creating object for Welcome class
// This will called default constructor
Welcome obj = new Welcome();
Console.Read();
}
}

}
Note: Destructor will call after execution of the program.

Вам также может понравиться