T3 - Object Oriented Programming in C#

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 64

C# and .

NET Technology

Theory 1: Object Oriented


Programming in C#
Objectives

 Essentials of Object-Oriented
Programming
 Classes and Objects
 Using Encapsulation

 C# and Object Orientation

 Defining Object-Oriented Systems

 The Object Hierarchy

C#.NET/ 2 of 106
Objectives
 Use Constructors In C#
 Use Destructors In C#
 Explain the working of Garbage Collector
 Discuss Method Overloading
 Discuss Operator Overloading
 Use Inheritance in C#
 Discuss Overriding

C#.NET/ 3 of 106
Objectives
 Discuss Polymorphism
 Use Virtual Functions
 Discuss relationship between polymorphism and
inheritance
 Discuss Abstract Base classes
 Discuss the concept of Interfaces
 Use Interfaces
 Discuss Properties
 Discuss Indexers

C#.NET/ 4 of 106
Object – Oriented
Programming Overview
1. Object – Oriented Programming
History
Object-oriented programming has roots that can be
traced to the 1960s:
 As hardware and software became increasingly
complex, quality was often compromised.
 Researchers studied ways to maintain software quality
and developed object-oriented programming in part to
address common problems by strongly emphasizing
discrete, reusable units of programming logic.
 The methodology focuses on data rather than
processes, with programs composed of self-sufficient
modules (objects) each containing all the information
needed to manipulate its own data structure.

C#.NET/ 6 of 106
1. Object – Oriented Programming
History
 The Object-Oriented methodology focuses on data
rather than processes, with programs composed of
self-sufficient modules (objects) each containing all the
information needed to manipulate its own data
structure.
 This is in contrast to the existing modular programming
which had been dominant for many years that focused
on the function of a module
 An object-oriented program may thus be viewed as a
collection of cooperating objects, as opposed to the
conventional model, in which a program is seen as a list
of tasks (subroutines) to perform

C#.NET/ 7 of 106
2. OOP Fundamental Concepts
 Fundamental Concepts in OOP are:
 Class
 Object
 Instance
 Method
 Message passing
 Inheritance
 Abstraction
 Encapsulation
 Polymorphysm
 De-coupling

C#.NET/ 8 of 106
I. Classes and Objects
1. What is a class?
 A class define the abstract characteristics of a
thing (object), including the thing's
characteristics (its attributes, fields or
properties) and the thing's behaviors (the
things it can do, or methods, operations or
features).
 For example, the class Dog would consist of
traits shared by all dogs, such as:
 Breed and fur color (characteristics), and
 The ability to bark and sit (behaviors)

C#.NET/ 10 of 106
1. What is a class?

 In C#.NET, classes are declared using


the keyword class, as shown in the
following example:

C#.NET/ 11 of 106
An example: A class with its attributes,
fields, properties, methods,…

C#.NET/ 12 of 106
2. Members of a class
 The members of a class type are divided into the
following categories:
 Constants
 Fields
 Methods
 Properties
 Events
 Indexers
 Operators
 Constructors
 Destructors
 Types

C#.NET/ 13 of 106
2.1. Compare Properties and Public
Fields
 Properties can be recognize
by IDEs (such as Visual
Studio.NET) but public fields
 Properties are the hybrid of
fields and methods
 A property is like a clock-
knob: when you turn it, the
hour hand and the minute
hand and the second hand
are automatically adjusted

C#.NET/ 14 of 106
2.2. Constructor
 Whenever a class or struct is created, its
constructor is called. A class or struct may
have multiple constructors that take different
arguments.
 Constructors enable the programmer to set
default values, limit instantiation, and write
code that is flexible and easy to read.
 If you do not provide a constructor for your
object, C# will create one by default that
instantiates the object and sets member
variables to the default values
 Static classes and structs can also have
constructors

C#.NET/ 15 of 106
2.3. Destructor
 Destructors are used to destruct instances of classes.
 Destructors cannot be defined in structs. They are only used
with classes.
 A class can only have one destructor.
 Destructors cannot be inherited or overloaded.
 Destructors cannot be called. They are invoked
automatically.
 A destructor does not take modifiers or have parameters.
 The destructor implicitly calls Finalize on the base class of
the object.

C#.NET/ 16 of 106
2.4. Indexers

 Indexers allow you to index a class or a


struct instance in the same way as an
array
 An indexer is declared like a property
except that the name of the member is
this followed by a parameter list written
between the delimiters [ and ]

C#.NET/ 17 of 106
Indexer example

BEFORE

C#.NET/ 18 of 106
Indexer example

C#.NET/ 19 of 106
3. Access Modifiers
 Access modifiers are keywords used to specify the declared
accessibility of a member or a type. This section introduces the four
access modifiers:
 Public: The public keyword is an access modifier for types and type
members. Public access is the most permissive access level. There are
no restrictions on accessing public members
 Protected: The protected keyword is a member access modifier. A
protected member is accessible from within the class in which it is
declared, and from within any class derived from the class that declared
this member.
 Internal: Internal members are accessible only within files in the same
assembly. A common use of internal access is in component-based
development because it enables a group of components to cooperate in a
private manner without being exposed to the rest of the application code.
 Private: The private keyword is a member access modifier. Private
access is the least permissive access level. Private members are
accessible only within the body of the class or the struct in which they are
declared. Nested types in the same body can also access those private
members.

C#.NET/ 20 of 106
3. What is the meaning of “partial”
keyword?
 In .NET framework 2.0 or higher, Microsoft introduces
a very new modifier named “partial”.

 Before, the definition a a class must be placed in a


single source file.

 But now, with “partial” modifier, 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

C#.NET/ 21 of 106
“partial” class definition example

C#.NET/ 22 of 106
3. What is the meaning of “partial”
keyword?
 Reasons to use “partial” modifier:
 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

C#.NET/ 23 of 106
4. What is an Object?
 An Object is a pattern of a class.

 Exp: The class of Dog defines all


possible dogs by listing the
characteristics and behaviors they can
have; the object Lassie is one particular
dog, with particular versions of the
characteristics. A Dog has fur; Lassie
has brown-and-white fur.

C#.NET/ 24 of 106
4. What is an Object?
 In OOP, each object is capable of
receiving messages, processing data,
and sending messages to other objects
and can be viewed as an independent
'machine' with a distinct role or
responsibility.
 The actions (or "operators") on these
objects are closely associated with the
object.

C#.NET/ 25 of 106
5. What is an “Instance”

 The instance is the actual object created


at runtime (and placed in RAM).

 The set of values of the fields and


properties of a particular object is called
its state

C#.NET/ 26 of 106
6. Object Data (or Object State)

 Object data describes information for


individual objects

C#.NET/ 27 of 106
7. “static” keyword

 The static modifier can be used with


classes, fields, methods, properties,
operators, events, and constructors

 But “static” keyword cannot be used with


indexers, destructors, or types other than
classes.

C#.NET/ 28 of 106
7. “static” keyword example

C#.NET/ 29 of 106
7. “static” keyword
 The static modifier on a class means that the class
cannot be instantiated, and that all of its members are
static.

 A static member has one version regardless of how


many instances of its enclosing type are created.

 A constant is implicitly a static member.

 A static member cannot be referenced through an


instance. Instead, it is referenced through the type
name

C#.NET/ 30 of 106
8. Nested Classes

 A class defined within a class or struct is


called a nested class

C#.NET/ 31 of 106
II. Encapsulation
1. What is encapsulation?
 Encapsulation is the hiding of the internal
mechanisms and data structures of a software
component behind a defined interface, in such a way
that users of the component (other pieces of software)
only need to know what the component does, and
cannot make themselves dependent on the details of
how it does it.

 For example, the Dog class has a bark() method. The


code for the bark() method defines exactly how a bark
happens (e.g., by inhale() and then exhale(), at a
particular pitch and volume). Timmy, Lassie's friend,
however, does not need to know exactly how she
barks.

C#.NET/ 33 of 106
2. Why must encapsulate?
 The purpose of encapsulation is to achieve
potential for change: the internal mechanisms
of the component can be improved without
impact on other components, or the
component can be replaced with a different
one that supports the same public interface.

 Encapsulation also protects the integrity of the


component, by preventing users from setting
the internal data of the component into an
invalid or inconsistent state.

C#.NET/ 34 of 106
2. Why must encapsulate?

 Encapsulation reduces system


complexity and thus increases
robustness, by limiting the
interdependencies between software
components

C#.NET/ 35 of 106
III. Inheritance
1. What is the inheritance?
 Inheritance is a way to form new
classes (instances of which are called
objects) using classes that have already
been defined.
 The inheritance concept was invented in
1967
 The new classes, known as derived
classes, take over (or inherit) attributes
and behavior of the pre-existing classes

C#.NET/ 37 of 106
Inheritance - Examples

C#.NET/ 38 of 106
2. Single and Multiple inheritances

 Single inheritance: deriving from one


base class
 Multiple inheritance: deriving from two or
more base classes

C#.NET/ 39 of 106
3. What are Over-loads?

 Overloading is the technical term for decl


aring two or more methods in the same s
cope with the same name
 By specifying different number of
parameters
 By specifying different types of parameters

C#.NET/ 40 of 106
4. Operator Over-loading
 Like C++, C# allows you to overload operators
for use on your own classes. This makes it
possible for a user-defined data type to look as
natural and be as logical to use as a
fundamental data type

 To overload an operator, you write a function


that has the name operator followed by the
symbol for the operator to be overloaded

C#.NET/ 41 of 106
5. Hiding Base Class Members
 Sometimes derived class members have the same
name as a corresponding base class member. In this
case, the derived member is said to be "hiding" the
base class member

 When hiding occurs, the derived member is masking


the functionality of the base class member. Users of the
derived class won't be able to see the hidden member;
they'll see only the derived class member

C#.NET/ 42 of 106
7. “base” keyword
 The base keyword is used to access members
of the base class from within a derived class:
 Call a method on the base class that has been
overridden by another method.
 Specify which base-class constructor should be
called when creating instances of the derived class.
 A base class access is permitted only in a
constructor, an instance method, or an
instance property accessor.
 It is an error to use the base keyword from
within a static method.

C#.NET/ 43 of 106
7. “base” keyword example

C#.NET/ 44 of 106
8. “sealed” keyword
 When applied to a class, the sealed modifier
prevents other classes from inheriting from it

 You can also use the sealed modifier on a


method or property that overrides a virtual
method or property in a base class. This
enables you to allow classes to derive from
your class and prevent them from overriding
specific virtual methods or properties.

C#.NET/ 45 of 106
8. “sealed” keyword example

 In the following example, no class can


inherit from class Musician.

C#.NET/ 46 of 106
8. “sealed” keyword example
 In the following example, Z inherits from Y but
Z cannot override the virtual function F that is
declared in X and sealed in Y.

C#.NET/ 47 of 106
8. “sealed” keyword
 Notes:
 When you define new methods or properties in a
class, you can prevent deriving classes from
overriding them by not declaring them as virtual.
 It is an error to use the abstract modifier with a
sealed class, because an abstract class must be
inherited by a class that provides an
implementation of the abstract methods or
properties.
 When applied to a method or property, the sealed
modifier must always be used with override.
 Because structs are implicitly sealed, they cannot
be inherited.

C#.NET/ 48 of 106
8. “new” keyword

 In C#, the new keyword can be used as


an operator or as a modifier.
 new operator   Used to create objects on
the heap and invoke constructors.
 new modifier   Used to hide an inherited
member from a base class member.

C#.NET/ 49 of 106
8. “new” keyword examples

 In the following example, “new” keyword


is used as an operator

C#.NET/ 50 of 106
8. “new” keyword examples

 In the following example, “new” keyword


is used as a modifier:

C#.NET/ 51 of 106
9. Why use inheritances?
 Enables a series of classes to be related
together according to their common
parts:
 common members only specified once, in
base class
 can be accessed in objects of all classes
derived from the base class
 Increases efficiency of production and
flexibility

C#.NET/ 52 of 106
IV. Polymorphism
1. What is the polymorphism?
 Polymorphism is derived from two Greek words. Poly (meaning
many) and morph (meaning forms). Polymorphism means many
forms

 Understanding Polymorphism is crucial to any OO language


professional , be it a Java , C++ or C# programmer

 If a Dog is commanded to speak(), it may emit a bark, while if a


Pig is asked to speak(), it may respond with an oink. Both inherit
speak() from Animal, but their subclass methods override the
methods of the superclass, known as overriding polymorphism

 We implement polymorphism by using virtual and override


keywords

C#.NET/ 54 of 106
Polymorphysm example
Về mặt hình thức, đối số
đầu vào của hàm Speak
phải có kiểu là Animal,
và khi hàm này được
gọi, thì phương thức
Speak của Animal đó sẽ
được gọi và sẽ không in
ra nội dung gì

Nhưng thực tế, khi truyền đối số


đầu vào cho hàm Speak, lúc là
Pig, lúc là Dog, thì hàm Speak lại
lúc thì gọi hàm Speak của Pig, lúc
thì lại gọi hàm Speak của Dog =>
Chính vì lý do này, hàm Speak
được gọi là “đa hình”

C#.NET/ 55 of 106
3. “override” and “virtual” keywords

 “override” and “virtual” keywords are used to


implement polymorphism in C#.NET
 The override modifier is required to extend or
modify the abstract or virtual implementation of
an inherited method, property, indexer, or
event
 The virtual keyword is used to modify a
method, property, indexer, or event declaration
and allow for it to be overridden in a
derived class

C#.NET/ 56 of 106
4. Why polymorphism?

 Why include polymorphism in a


programming language?

 Because it significantly reduces


programming effort. In particular,
polymorphism allows you to write one
method for a variety of types, rather than
to write one method per type

C#.NET/ 57 of 106
V. Abstractions:
Abstract Base Classes &
Interfaces
1. What is the abstraction?
 Abstraction (from the Latin abs, meaning away
from and trahere, meaning to draw) is the
process of taking away or removing
characteristics from something in order to
reduce it to a set of essential characteristics
 In object-oriented programming, abstraction is
one of three central principles (along with
encapsulation and inheritance)

C#.NET/ 59 of 106
1. What is the abstraction?

 Through the process of abstraction, a


programmer hides all but the relevant
data about an object in order to reduce
complexity and increase efficiency

C#.NET/ 60 of 106
2. Abstract base classes
 Abstract base classes are classes that cannot
be instantiated, and are frequently either
partially implemented, or not at all
implemented.

 In C#, the abstract modifier is used to declare


an abstract class

C#.NET/ 61 of 106
3. Interfaces
 An interface is a collection of method
definitions (without implementations) and
constant values.
 An interface is like a pure abstract base
class
 Notes:
 A class that implements a particular
interface must implement the members
listed by that interface

C#.NET/ 62 of 106
4. Why must make everything
abstract?
 The importance of abstraction is derived from
its ability to hide irrelevant details and from the
use of names to reference objects.
 Abstraction is essential in the construction of
programs. It places the emphasis on what an
object is or does rather than how it is
represented or how it works. Thus, it is the
primary means of managing complexity in
large programs

C#.NET/ 63 of 106
5. Differences between Abstract
Classes Vs. Interfaces
 The biggest difference between an
abstract class and an interface is: A
class may implement an unlimited
number of interfaces, but may inherit
from only one abstract

C#.NET/ 64 of 106

You might also like