Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C Sharp OOPs 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Object Oriented Programming (OOP) Concepts

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

Class Example

/* fields,

Variables,

Methods,

Properties,

*/

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

class BaseClass

class DerivedClass : BaseClass

{
}

Now an object of a derived class can use the accessible properties of the base class without defining
it in the derived class.

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 “Don’t
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.

Abstraction
Abstraction is defined as showing only the relevant data to the user. Generally abstraction and
encapsulation are explained in confusing manners.

Example

So just take an example of Mobile Phone Design.

Relevant Features of a phone in which the user is interested are Camera, Music player, calling
function, Voice recording and so on.

Irrelevant Features of a phone in which the user is not interested are circuit board design, hardware
used and so on.

So in designing the Mobile Phone Model, both relevant and irrelevant features are required. But we
need to show only relevant features. So we design a Mobile Phone in such a way that only relevant
features are shown and irrelevant features are hidden. And remember one thing, that deciding
relevant and irrelevant features is totally a user choice.

Polymorphism
Polymorphism is defined as the implementation of the same method with different attributes in a
different context.

Example

For example, we have a class named shape with a method name buildshape(). We need to use it in
the class Circle, class triangle and the class quadrilateral. So for every class we use the buildshape()
method but with different attributes.
ENCAPSULATION

Encapsulation is the first pillar or principle of object-oriented programming. In simple words,


“Encapsulation is a process of binding data members (variables, properties) and member functions
(methods) into a single unit”. And Class is the best example of encapsulation.

Through encapsulation a class can hide the internal details of how an object does something.
Encapsulation solves the problem at the implementation level.

A class can specify how accessible each of its members (variables, properties, and methods) is to
code outside of the class. Encapsulation simplifies the interaction between objects. An object can
use another object without knowing all its data or how its data is maintained. For example, a Client
object might have name, address, company, and department properties. If a Bank object wants to
use a Client object, it can request the name and address for the bank without needing to know the
company and department details of the Client object.

With the help of encapsulation, a class can change the internal implementation without hurting the
overall functionality of the system.

Need or purpose of encapsulation


To hide and prevent code (data) from the outside world (here the world means other classes and
assemblies).

To prevent code (data) from accidental corruption due to programming errors so that we can deliver
expected output. Due to programming mistakes, code may not behave properly and it has an effect
on data and then it will affect the functionality of the system. With encapsulation we can make
variables, properties, and methods private so it is not accessible to all but accessible through proper
channels only to protect it from accidental corruption from other classes.

To have a class better control over its fields (validating values etc…).

Ways to achieve encapsulation with code example

We can achieve encapsulation by the following ways. Take a look at the methods to achieve
encapsulation with code example:

public class Account

private string accoutName;

// get methods

public string GetAccount()

return accoutName;

}
// Set method

public void SetAccount(string name)

accoutName = name;

static void Main()

string name ="SAVING_ACCOUNT";

Account account = new Account();

account.SetAccount(name);

name = string.Empty;

name = account.GetAccount();

In the above example we use the get and set methods (GetAccount and SetAccount) to return
account and set account name. We use the private variable accountName and as it is not accessible
directly, to use this variable, we use the get and set methods.

By using properties (read only properties, write only properties)

Like the above example we can achieve encapsulation using properties also.

We can use a property (which has a get and set part), or we can use a read only property (which has
only a get part) or we can also use a write only property (which has only a set part). But in all cases
we can achieve encapsulation.

Have a look at the following example using properties.

// Encapsulation using properties

public class Account

private string accoutName="SAVING_ACCOUNT";

// property which has get and set

public string AccoutName

get

{
return accoutName;

set

accoutName = value;

private string address="India";

// readonly property

public string Address

get

return address;

private string phone = "1234567890";

// writeonly property

public string Phone

set

phone=value;

static void Main()

// Encapsulation using properties

string name = string.Empty;


Account account = new Account();

// call get part

name = account.AccoutName;

// change the value

name = "CURRENT_ACCOUNT";

// call set part

account.AccoutName = name;

string address = string.Empty;

// call readonly property

address = account.Address;

// now address has value “India”

string phone = "1234567890";

// call writeonly property

account.Phone = phone;

// now account.Phone has value “1234567890”

Here when we create a new instance of the account class, all the private variables in the account
class (account name, address, and phone) are assigned with values. In the main class we can skip the
variables (name, address, and phone) and directly use System.Console to write the output. I use the
variables so that during debugging we can check how the values of the variables in the main class
change after every call to the properties.

Types of Constructor with example


Constructor is like a special method/methods of the class that will be automatically invoked when an
instance of the class is created. Constructor is used to initialize values to fields in a class.

Different types of Constructors are:

 Default Constructor
 Parameterized Constructor
 Copy Constructor
 Static Constructor
 Private Constructor

Default Constructor: A constructor without any parameters is called as default constructor.


Drawback of default constructor is every instance of the class will be initialized to same values and it
is not possible to initialize each instance of the class to different values.
Please follow the attached class room demo program to see example of Default Constructor.

Parameterized Constructor: A constructor with at least one parameter is called as parameterized


constructor. Advantage of parameterized constructor is you can initialize each instance of the class
to different values.

Example for Parameterized Constructor

using System;

namespace ProgramCall

class Test1

//Private fields of class

int A, B;

//default Constructor

public Test1()

A = 10;

B = 20;

//Paremetrized Constructor

public Test1(int X, int Y)

A = X;

B = Y;

}
//Method to print

public void Print()

Console.WriteLine("A = {0}\tB = {1}", A, B);

class MainClass

static void Main()

Test1 T1 = new Test1(); //Default Constructor is called

Test1 T2 = new Test1(80, 40); //Parameterized Constructor is called

T1.Print();

T2.Print();

Console.Read();

}
Output

A = 10 B = 20

A = 80 B = 40

Copy Constructor: A parameterized constructor that contains a parameter of same class type is
called as copy constructor. Main purpose of copy constructor is to initialize new instance to the
values of an existing instance.

Example for Copy Constructor

using System;

namespace ProgramCall

class Test2

int A, B;

public Test2(int X, int Y)

A = X;

B = Y;

//Copy Constructor

public Test2(Test2 T)

A = T.A;
B = T.B;

public void Print()

Console.WriteLine("A = {0}\tB = {1}", A, B);

class CopyConstructor

static void Main()

Test2 T2 = new Test2(80, 90);

//Invoking copy constructor

Test2 T3 = new Test2(T2);

T2.Print();

T3.Print();

Console.Read();
}

Output

A = 80 B = 90

A = 80 B = 90

Static Constructor : You can create a constructor as static and when a constructor is created as
static, it will be invoked only once for any number of instances of the class and it is during the
creation of first instance of the class or the first reference to a static member in the class. Static
constructor is used to initialize static fields of the class and to write the code that needs to be
executed only once.

Example for Static Constructor

using System;

namespace ProgramCall

class Test3

public Test3()

Console.WriteLine("Instance Constructor");

static Test3()
{

Console.WriteLine("Static Constructor");

class StaticConstructor

static void Main()

//Static Constructor and instance constructor, both are invoked for first instance.

Test3 T1 = new Test3();

//Only instance constructor is invoked.

Test3 T2 = new Test3();

Console.Read();

Output

Static Constructor

Instance Constructor

Instance Constructor

Private Constructor : You can also create a constructor as private. When a class contains at least one
private constructor, then it is not possible to create an instance for the class. Private constructor is
used to restrict the class from being instantiated when it contains every member as static.
Some unique points related to constructors are as follows

 A class can have any number of constructors.


 A constructor doesn’t have any return type even void.
 A static constructor cannot be a parameterized constructor.
 Within a class you can create only one static constructor.

ASSIGNMENT QUESTIONS

Programming:

Create a class "Product" having 2 data members ProductId (int) and ProductName (string)

Create a class "Purchase" having 2 data members ProductId (int) and PurchaseQuantity (int)

Create a class "Sales" having 2 data members ProductId (int) and SalesQuantity (int)

In Program.cs create objects of all 3 classes. Accept data to all of them.

Calculate StockQuantity (i.e. StockQuantity = PurchaseQuantity - SalesQuantity )

Display : ProductId, ProductName and StockQuantity

Theory:

1. Write notes on “static” keyword with example. How does it behave when used against any
variable or member function?
2. Why C# is called fully object oriented programming?
3. Write a short note on ENCAPSULATION, and explain various elements/members used in a
class.
4. Explain about following constructor with example :
 Default Constructor
 Parameterized Constructor
 Copy Constructor
5. What is Destructor? What is the sequence of de-initialization of data through destructor in
case you have multiple object of same class ?
6. What is a property? What is advantages of property over fields in a class?

You might also like