0% found this document useful (0 votes)
13 views24 pages

Oop PDF

Uploaded by

Leonardo Hidrovo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views24 pages

Oop PDF

Uploaded by

Leonardo Hidrovo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

OBJECT ORIENTED

PROGRAMMING - FUNDAMENTAL
CONCEPTS

BY LEONARDO HIDROVO
08-25-2014
CONTENTS

1. Fundamental Principles of OOP


2. Inheritance
3. Abstraction
4. Encapsulation
5. Polymorphism
6. Cohesion and Coupling
FUNDAMENTAL PRINCIPLES OF OOP
 Inheritance
• Inherit members from parent class
 Abstraction
• Define and execute abstract actions
 Encapsulation
• Hide the internals of a class
 Polymorphism
• Access a class through its parent interface
CLASSES AND INTERFACES

 Classes define attributes and behavior


• Fields, properties, methods, etc.
• Methods contain code for execution
public class Patient { … }

 Interfaces define a set of operations


• Empty methods and properties, left to be implemented later
public interface IDBContext{ … }
INHERITANCE

 Inheritance allows child classes inherits the characteristics of existing parent class
• Attributes (fields and properties)
• Operations (methods)
 Child class can extend the parent class
• Add new fields and methods
• Redefine methods (modify existing behavior)
 A class can implement an interface by providing implementation for all its
methods
INHERITANCE – BENEFITS

 Inheritance has a lot of benefits


• Extensibility
• Reusability
• Provides abstraction
• Eliminates redundant code
 Use inheritance for buidling is-a relationships
• For example. dog is-a animal (dogs are kind of animals)
 Don't use it to build has-a relationship
• For example. dog has-a name (dog is not kind of name)
Base class
Person
+Name: String
+Address: String

Derived class Derived class

Employee Student
+Company: String +School: String
+Salary: double
INHERITANCE IN .NET

 A class can inherit only one base class


• For example: IOException derives from SystemException and it derives from
Exception
 A class can implement several interfaces
• For example: List<T> implements IList<T>, ICollection<T>, IEnumerable<T>
 An interface can implement several interfaces
• For example: IList<T> implements ICollection<T> and IEnumerable<T>
ACCESSIBILITY LEVELS
Access modifiers in C#
• public – access is not restricted
public string name;
• private – access is restricted to the containing type
private int index;
• protected – is accessible in a derived class only if the access
occurs through the derived class type.
protected string name;
• internal – Internal types or members are accessible only within
files in the same assembly.
internal string name;
EXAMPLE OF INHERITANCE AND ACCESSIBILITY

class Creature
{
protected string Name { get; private set; }
private void Talk()
{
Console.WriteLine("I am creature ...");
}
protected void Walk()
{
Console.WriteLine("Walking ...");
}
}
class Mammal : Creature
{
// base.Talk() can be invoked here
// this.name can be read but cannot be modified here
}
IMPORTANT ASPECTS
 Structures cannot be inherited
 In C# there is no multiple inheritance
• Only multiple interfaces can be implemented

 Instance and static constructors are not inherited


 Inheritance is transitive relation
• If C is derived from B, and B is derived from A, then C inherits A as well
 A derived class extends its base class
• It can add new members but cannot remove derived ones
 Declaring new members with the same name or signature hides the inherited ones
 A class can declare virtual methods and properties
• Derived classes can override the implementation of these members
• E.g. Object.Equals() is virtual method
ABSTRACTION
• Abstractionmeans ignoring irrelevant features, properties, or functions and
emphasizing the relevant ones ...

"Relevant" to what?

• ... relevant to the given project (with an eye to future reuse in similar projects)
• Abstraction = managing complexity
ABSTRACTION
 Abstraction is something we do every day
• Looking at an object, we see those things about it that have meaning to us
• We abstract the properties of the object, and keep only what we need
• E.g. students get "name" but not "color of eyes"
 Allows us to represent a complex reality in terms of a simplified model
 Abstraction highlights the properties of an entity that we need and
hides the others
 In .NET abstraction is achieved in several ways:
• Abstract classes
• Interfaces
• Inheritance
ENCAPSULATION

 Encapsulation hides the implementation details


 Class announces some operations (methods) available for its clients – its
public interface
 All data members (fields) of a class should be hidden
• Accessed via properties (read-only and read-write)
 No interface members should be hidden
ENCAPSULATION IN .NET
 Fields are always declared private
• Accessed through properties in read-only or read-write mode
 Constructors are almost always declared public
 Interface methods are always public
• Not explicitly declared with public
 Non-interface methods are declared private / protected
BENEFITS
 Ensures that structural changes remain local:
• Changing the class internals does not affect any code outside of the class
• Changing methods' implementation
does not reflect the clients using them
 Encapsulation allows adding some logic when accessing client's data
• E.g. validation on modifying a property value
POLYMORPHISM
Polymorphism = ability to take more than one form (objects
have more than one type)
• A class can be used through its parent interface
• A child class may override some of the behaviors of the parent
class
Polymorphism allows abstract operations to be defined and
used
• Abstract operations are defined in the base class' interface and
implemented in the child classes
• Declared as abstract or virtual
Why handle an object of given type as object of its base type?
• To invoke abstract operations
• To mix different related types in the same collection
E.g. List<object> can hold anything
• To pass more specific object to a method that expects a parameter of a more generic
type
• To declare a more generic field which will be initialized and "specialized" later

Virtual method is method that can be used in the same way on instances of
base and derived classes but its implementation is different
A method is said to be a virtual when it is declared as virtual
public virtual void GetDataContext()

Methods that are declared as virtual in a base class can be overridden using
the keyword override in the derived class
Using override we can modify a method or property
An override method provides a new implementation of a member inherited from
a base class
You cannot override a non-virtual or static method
The overridden base method must be virtual, abstract, or override
Polymorphism ensures that the appropriate method of the subclass is called
through its base class' interface
Polymorphism is implemented using a technique called late method binding
Exact method to be called is determined at runtime, just before performing the
call
Applied for all abstract / virtual methods
Note: Late binding is slower than normal (early) binding
COHESION AND COUPLING
Cohesion describes how closely all the routines in a class or all the code in a
routine support a central purpose
Cohesion must be strong
• Well-defined abstractions keep cohesion strong
Classes must contain strongly related functionality and aim for single purpose
Cohesion is a useful tool for managing complexity

Strong cohesion example


Class Math that has methods:
Sin(), Cos(), Asin()
Sqrt(), Pow(), Exp()
Math.PI, Math.E
STRONG COHESION EXAMPLE
CLASS MATH THAT HAS METHODS:
SIN(), COS(), ASIN()
SQRT(), POW(), EXP()
MATH.PI, MATH.E
double sideA = 40, sideB = 69;
double angleAB = Math.PI / 3;

double sideC =
Math.Pow(sideA, 2) + Math.Pow(sideB, 2)
- 2 * sideA * sideB * Math.Cos(angleAB);

double sidesSqrtSum = Math.Sqrt(sideA) +


Math.Sqrt(sideB) + Math.Sqrt(sideC);
Bad cohesion example
Class “Magic” that has these methods:

public void PrintDocument(Document d)

public void SendEmail(


string recipient, string subject, string text)

public void CalculateDistanceBetweenPoints(


int x1, int y1, int x2, int y2)

public void OpenDBConnection()


COUPLING
Coupling describes how tightly a class or routine is related to
other classes or routines
Coupling must be kept loose
• Modules must depend little on each other
• All classes and routines must have small, direct, visible, and flexible
relations to other classes and routines
• One module must be easily used by other modules
Loose Coupling: Tight Coupling:
• Easily replace old HDD • Where is the video
• Easily place this HDD to adapter
another motherboard • Can you change the
video controller
LOOSE COUPLING – EXAMPLE
class Report
{
public bool LoadFromFile(string fileName) {…}
public bool SaveToFile(string fileName) {…}
}
class Printer
{
public static int Print(Report report) {…}
}
class Program
{
static void Main()
{
Report myReport = new Report();
myReport.LoadFromFile("C:\\DailyReport.rep");
Printer.Print(myReport);
}
}
TIGHT COUPLING – EXAMPLE
class MathParams
{
public static double operand;
public static double result;
}
class MathUtil
{
public static void Sqrt()
{
MathParams.result = CalcSqrt(MathParams.operand);
}
}
class MainClass
{
static void Main()
{
MathParams.operand = 64;
MathUtil.Sqrt();
Console.WriteLine(MathParams.result);
}
}

You might also like