Sunteți pe pagina 1din 33

Object Oriented Programming

Overview :
 Object Oriented Approach

 Life Cycle of an object

 Access Specifiers

 Access Modifiers

 Inheritance

 Properties

 Polymorphism

 Overloading

 Function Overloading

 Overriding

 Interface

 Abstract

 Sealed

 Collection

 Indexers

 Delegates

 Events
Object Oriented Approach

 The concept behind the object-oriented approach is to combine data and its

functions into a single unit.

 The data pertaining to an object is also known as an attribute.

 The functions of an object are also known as methods.

 An object’s functions provide the only way to access its data. Thus, the data

available in an object is protected from accidental alteration.

Object Oriented Programming

 Problem solving technique to develop software systems.

 Technique to think real world in terms of objects.

 Object maps the software model to real word concept. These objects have

responsibilities and provide services to application or other services.


Components of Object Oriented Programming

Class

A group of objects which have similar data and methods is called a class.

Object

An object is an instance of a class.

For example if student is a class, then Michael and John are instances. The data

components that are common among these objects are Name, Batch code etc., and the

functions that are common are Attend_class(), Attend_test() etc.

Inheritance

Inheritance is the process of creating a new class, called the derived class, from an

existing class, called the base class.

Reusability

The concept of inheritance provides for reusability of existing classes and their

functions.

Polymorphism

The concept of using operators or functions in different ways is called polymorphism.


Life Cycle of an Object

Every object has a life cycle, from using class definition to its destruction.

There are two important stages in object's life cycle :-

 Constructor

 Destructor

Constructor

 A constructor is a member that is used to perform actions required to initialize

an instance of a class.

 A constructor has to be declared using the public access specifier.

 A class can have multiple constructors.

 The constructor method should have the same name as the class.
Destructor

 A destructor is a member that is used to destroy an object of a class.

 A destructor is a method with the same name as the class preceded by the

symbol, ~.

 A destructor cannot take parameters. & A class can have only one destructor.

Automatic Memory Management

Garbage collection:

 Is a process that automatically frees the memory of objects that are no more in

use.

 Enables a programmer to automatically free allocated memory.

 Identifies the objects that are no more referenced in the program and releases

the memory allocated to them.


Access Specifier

Access specifiers are used to limit the accessibility of the data members and functions

in a class. The accessibility of class members can be specified using the keywords:

 Public

 Protected

 Private

 Internal

 Protected internal

Access Specifier

 public - member accessible from any code

 private - member accessible only from code that is part of the class

 internal - member accessible only from code within the project (assembly)

where it is defined.

 protected - member accessible only from code that is part of the class or a

derived class.

 protected internal - member accessible from code derived classes within the

project or assembly.
Access Modifiers

 Modifiers determine how the data members and methods are used in other

classes and objects.

 A class declaration can include a sequence of access modifiers.

 Access modifiers can also be applied to methods.

 The different access modifiers that can be used in a C-Sharp program are:

 static

 sealed

 abstract

 virtual
Access Modifier - Static

The features of a static modifier are:

 A static modifier allows a variable or method to be associated with its class and

not a class instance.

 A class cannot be declared static.

 Static members are shared by all the instances of a class.

 A static member can be accessed using the class name.

Access Modifier - Sealed

The sealed modifier

 Does not allow a class to be inherited.

 Is used to create classes in which the methods cannot be overridden.

 Is used to create standard classes that cannot be derived.

 Does not allow a method to be overridden.


Access Modifier - Abstract

The abstract modifier:

 Is used to define an incomplete class that is referred to as the abstract class.

 An abstract class can act as the base class for other classes.

 An abstract class cannot be instantiated directly.

 An abstract class cannot be sealed.

 An abstract method is one in which the method definition is not given.

Access Modifier - Virtual

The feature of the virtual modifier are:

 A virtual modifier is used to declare a virtual method.

 A virtual method cannot include static, abstract or override modifier.

 It should be subclassed.
Inheritance

The main aim of inheritance is to improve code reusability.

 This is done by creating classes that derive properties from other classes and

are known as derived classes.

 The class from which the derived class derives properties is known as the base

class.

 Classes support single inheritance.

The Object class is the ultimate base class for all classes.

Different Forms of Inheritance :-

 Single inheritance (Only one superclass)

 Multiple Inheritance ( several super classes)

 Hierarchical inheritance ( one superclass, many subclasses)

 Multilevel inheritance (subclass derived from another subclass)


Some of the important aspects of Inheritance :-

 Inheritance is transitive. If C is derived from B, and B is derived from A, then

C inherits the members declared in B as well as the members declared in A.

 A derived class extends its direct base class. A derived class can add new

members to those it inherits, but it cannot remove the definition of an

inherited member.

 A derived class can hide inherited members by declaring new members with

the same name or signature. Note however that hiding an inherited member

does not remove the member - it merely makes the member inaccessible in the

derived class.
Properties

A property is a member that holds data of an object or a class. Properties are the

natural extensions of fields both are named members with associated types and the

syntax for accessing fields properties is same.

Properties are classified as Static & Instance. Static property is not associated with a

specific instance and cannot be referenced through an instance.

The accessor of a property contains the executable statements associated with getting

(reading or computing ) or setting (writing) the property.

There are two types of accessors.

 get ( readonly property)

 set ( writeonly property)

Get accessor corresponds to a parameterless method with a return value of the

property type. And the body of a get accessor must conform to the rules for value

returning methods.

Set accessor corresponds to a method with a single value parameter of the property

type and a void return type.


Polymorphism

Polymorphism means the ability to take more then one form.

For example , an operation may exhibit different behavior in different instances. The

behavior depends upon the types of data used in the operation.

The concept of polymorphism is often expressed by the phrase "one interface

multiple methods". This means that it is possible to design a generic interface to a

group of related activities.

The specialized forms of polymorphism :-

 static binding

 dynamic binding

 And the form of method overloading and overriding in c#.

Binding

It refers to the linking of a method call to the code to be executed in response to the call.
Static Binding

The object checks for a method call in the class. The method when found is

executed. when this happens at the compile time, it is called static polymorphism.

Dynamic Binding

Sometimes it is not possible for the compiler to decide which method should be

called. It means that the code associated with a given procedure call is not known

until the time of the call at runtime. this happens when the same method name is

used to perform different functionality by overriding it in the derived or sub class.

Difference between Overloading & Overriding

 Overloading takes place within the same class i.e., Overloaded forms of same

function or within the same class.

 Where as in overriding when the class is subclassed and the function is made

to perform different functionality in the subclass it is referred to as overriding.


Overloading / Function overloading

 Function overloading is the concept of using the same name for two or more

functions.

 Each redefinition of the function should have a unique signature.

 Function overloading is used to implement Polymorphism.

A function signature consists of the:

 Method name

 Type of parameters

 Sequence of parameters

 Number of parameters

The resolution of an overloaded function depends on the list of arguments and a set

of candidate member functions and the selection of the function to invoke is as

follows:

 By the invocation of a named method

 By the invocation of a constructor


The selection of the best function to be invoked is done from a set of applicable

candidate functions.

A member is called a candidate function based on the argument list.

A function is a best member function, when its arguments match the function called.

The new operator is used to create new instances of a class.

The new operator can be used as follows:

 In object creation

 In array creation

Overriding

 Overriding is used to improve or modify the functionality of existing methods.

 A base class member can be overridden by defining a derived class member

with the same name as that of the base class member.

 The keyword override is used to define a method in the derived class that

overrides the method of the base class.


Interface

 An interface is a contract that contains a collection of function prototypes.

 You can implement the interface functions in a class in order to derive

from an interface.

Interfaces can contain:

 Methods

 Properties

 Indexers

 Events
Abstract Class

 A class that provides common behavior across a set of subclasses, but is not
itself designed to have instances that work.

 If you would like to make classes that only represent base classes, and
don’t want anyone to create objects of these class types.

 It is used to indicate that a class is incomplete and that it is intended to be


used only as a base class.

 An abstract class cannot be instantiated.

 An abstract class is permitted (but not required) to contain abstract

members.

 An abstract class cannot be sealed.

 An abstract method cannot be private.

 If you declare an abstract method as protected, it should be protected in

its derived class.

 An abstract method cannot have the modifier virtual, because an abstract

method is implicitly virtual.

 An abstract member cannot be static


Sealed Class

 A sealed class cannot be used as a base class.

 For this reason, it cannot also be an abstract class.

 Sealed classes are primarily used to prevent derivation.

 Sealing a class means one can not derive from it.

 Sealing a method means one can not override it.

Difference between Abstract Class & Interface

 Interface cannot provide any implementation for the methods and properties

where as class can provide an implementation to the method which can be

overridden in the child class.

 Interface cannot define any constructor where as class can.

 A class can inherit only from a single class and its uses inherits keyword for

doing so. A class can implement multiple interfaces and uses implements

keyword for doing so.


 In an interface class, all methods must be abstract.

 In an abstract class some methods can be concrete.

 In an interface class, no accessibility modifiers are allowed, which is ok in an

abstract class.

this Keyword

As with base, this can also be used within class members, and like base, this

keyword refers to an object instance.

Nested class

Nested Classes are classes within the classes.


Collections

Collections are the objects that can contain arrays of other objects and contain

functionality that controls access to the objects. Collection classes are generally used

for maintains list of objects and may expose additional functionality over arrays.

This functionality comes through implementing interfaces from System.Collections

namespace.

There are number of interfaces in System.Collections namespace that provide

basic collection functionality :-

IEnumerable – Provides the capability to loop through items of collection.

ICollection – Provides ability to obtain the number of items in a collection, and to

copy in simple array type.

IList – Provides list of items for collection as well as capability for accessing these

elements.
Types of Collections

 Stack -> L I F O

 Queue -> F I F O

 ArrayList -> Array is whose size can increase and decrease dynamically. It

can hold items of different types. It can increase and decrease size dynamically

you don't have to use REDIM keyword . You can access any item in array

using the INDEX value of the array position.

 Hashtable -> You can access array using INDEX value of array, but how many

times you know the real value of index. Hashtable provides way of accessing

the index using a user identified KEY value, thus removing the INDEX

problem.

 SortedArrayList ->It works like Arraylist in the sorted manner.


Indexers

It is a special kind of property that we can add to a class to provide array like

access. However we can define and use complex parameter type with the square

brackets syntax.

Delegates

It allows the programmer to encapsulate a reference to a method inside a delegate

object. The advantage is object Oriented, type safe and secure. Multicast delegate is

a delegate that points to and eventually fires off several methods.

Declaration :- delegate void MyDelegate();

Instantiation :- MyDelegate dele = new MyDelegate(fun);

// Where void fun() is a function

Invocation : - dele(); // Delegate can be called using method

Events

Events are similar to exceptions in that they are raised by objects and we can supply

code that acts on them. It is a member that enables an object or class to provide

notifications. When an event occurs, all the event handlers are 'notified'. The event

declaration should have the keyword 'event' followed by the delagate type.
Exceptions

 An exception is an erroneous situation that occurs during program


execution.

 Exception-handling provides a structured and uniform way of handling


system-level and application-level errors.

 All exceptions are represented by an instance of a pre-defined class,


System.Exception.

 Exception (Base Class)

 IndexOutOfRangeException

 NullReferenceException

 ArgumentException

 ArrayTypeMismatchException

 OverflowException

 ArithmeticException

 DivideByZeroException

 InvalidOperationException

 Sending an exception object to the program for handling is known as


throwing the exception. It can be caught in a try and catch construct. The
finally statement can be used to clean up after the exception has been
handled.
 A try block can have multiple catch blocks. Therfore, it is essential that the
catch block specifies the type it can handle.

 Exceptions can be built-in or user defined. Though builtin exceptions are


handled by the system, the programmer must also handle them explicitly.

 User defined exceptions are useful in handling complicated error


conditions. Specialized catch blocks can be written to handle specific
exceptions.

What is the difference between Structure & Class

 Structure are value types and classes are reference types. So structures use
stack and classes use heap.

 Structure members can not be declared as protected, but class members


can be.

 You can use inheritance in class but not in structures

 You can use constructor in class but not in structures

 Objects created from classes are terminated using Garbage Collector.


Structure's are not.
C# 2.0
Overview :

 Generics

 Partial Types

 Nullable Types

 Iterator

 Anonymous Methods

 Static Class
Generics

 Generics are classes, structures, interfaces, and methods that have


placeholders (type parameters) for one or more of the types they store or
use.

 A generic collection class might use a type parameter as a placeholder for


the type of objects it stores; the type parameters appear as the types of its
fields, and the parameter types of its methods.

 A generic method might use its type parameter as the type of its return
value, or as the type of one of its formal parameters.

 The following code illustrates a simple generic class definition.

public class Generic<T>

public T Field;

 When you create an instance of a generic class, you specify the actual
types to substitute for the type parameters.

 This establishes a new generic class, referred to as a constructed generic


class, with your chosen types substituted everywhere that the type
parameters appear.

Generic<string> g = new Generic<string>();

g.Field = "A string";


Partial Class

 It is possible to split the definition of a class or a struct, or an interface over


two or more source files.

 Each source file contains a section of the class definition, and all parts are
combined when the application is compiled.

 There are several situations when splitting a class definition is desirable:

■ When working on large projects, spreading a class over separate


files allows multiple programmers to work on it simultaneously.

■ When working with automatically generated source, code can be


added to the class without having to recreate the source file. Visual
Studio uses this approach when creating Windows Forms, Web
Service wrapper code, and so on. You can create code that uses these
classes without having to edit the file created by Visual Studio.

To split a class definition, use the partial keyword modifier, as shown below:

public partial class Employee

public void DoWork()

}
public partial class Employee

public void GoToLunch()

Nullable Type

 Nullable types are instances of the System.Nullable struct.

 A nullable type can represent the normal range of values for its underlying
value type, plus an additional null value.

For example,

A Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value


from -2147483648 to 2147483647, or it can be assigned the null value.

A Nullable<bool> can be assigned the values true or false, or null. The ability to
assign null to numeric and Boolean types is particularly useful when dealing with
databases and other data types containing elements that may not be assigned a
value. For example, a Boolean field in a database can store the values true or
false, or it may be undefined.
Nullable types have the following characteristics:

 Nullable types represent value-type variables that can be assigned the value of
null. You cannot create a nullable type based on a reference type. (Reference
types already support the null value.)

 The syntax T? is shorthand for System.Nullable<T>, where T is a value type.


The two forms are interchangeable.

 Assign a value to a nullable type in the same way as for an ordinary value
type, for example int? x = 10; or double? D = 4.108;

 Use the System.Nullable.GetValueOrDefault property to return either the


assigned value, or the default value for the underlying type if the value is null,
for example int j = x.GetValueOrDefault();

 Use the HasValue and Value read-only properties to test for null and retrieve
the value, for example if(x.HasValue) j = x.Value;

 The HasValue property returns true if the variable contains a value, or false
if it is null. The Value property returns a value if one is assigned, otherwise a
System.InvalidOperationException is thrown.The default value for a nullable
type variable sets HasValue to false. The Value is undefined.

 Use the ?? operator to assign a default value that will be applied when a
nullable type whose current value is null is assigned to a non-nullable type,
for example int? x = null; int y = x ?? -1;

 Nested nullable types are not allowed. The following line will not compile:
Nullable<Nullable<int>> n;
Iterator

 Iterator is a section of code that returns an ordered sequence of values of


the same type.

 An iterator can be used as the body of a method, an operator, or a get


accessor.

 The iterator code uses the yield return statement to return each element in
turn. yield break ends the iteration. For more information, see yield.

 Multiple iterators can be implemented on a class. Each iterator must have


a unique name just like any class member, and can be invoked by client
code in a foreach statement as follows:

 foreach(int x in SampleClass.Iterator2){ }

The return type of an iterator must be IEnumerable, IEnumerator

 The “yield” keyword is used to specify the value, or values, returned.


When the yield return statement is reached, the current location is stored.
Execution is restarted from this location the next time the iterator is called.

 Iterators are especially useful with collection classes, providing an easy


way to iterate non-trivial data structures such as binary trees.
Anonymous Method

 Creating anonymous methods is essentially a way to pass a code block as a


delegate parameter

 By using anonymous methods, you reduce the coding overhead in


instantiating delegates by eliminating the need to create a separate method.

Static Classes

 Static classes and class members are used to create data and functions that
can be accessed without creating an instance of the class.

 Static class members can be used to separate data and behavior that is
independent of any object identity: the data and functions do not change
regardless of what happens to the object.

 Static classes can be used when there is no data or behavior in the class
that depends on object identity.

 A class can be declared static, indicating that it contains only static


members. It is not possible to create instances of a static class using the
new keyword. Static classes are loaded automatically by the .NET
Framework common language runtime (CLR) when the program or
namespace containing the class is loaded.
 Use a static class to contain methods that are not associated with a
particular object. For example, it is a common requirement to create a set
of methods that do not act on instance data and are not associated to a
specific object in your code. You could use a static class to hold those
methods.

 The main features of a static class are:

■ They only contain static members.

■ They cannot be instantiated.

■ They are sealed.

■ They cannot contain Instance

S-ar putea să vă placă și