You are on page 1of 58

Object-oriented

Programming
Concepts

Abstraction

A model of a complex system that includes only


thedetailsessential to the perspective of the viewer of
the system.

It simply means showing only those details to the user


which are of use to them, and hiding up the
unnecessaryportion.

Abstractions are the fundamental way that we manage


complexity.

Different viewers use different abstractions of a


particular system.

Example

While we see a car as a means of transportation, the


automotive engineer may see it as a large mass with
a small contact area between it and the road.

Advantages of Abstraction
Helps to manage the complexity of a large
system.
Supports our quality goals of modifiability
and reusability.
Most modifications can be localized to just a
few modules.
Supports thecreation of generic modules
that can be used in other systems.

Abstraction in .NET

In .NET abstraction is achieved in several


ways:
Abstract classes
Interfaces
Inheritance

Encapsulation
Encapsulation is way to hide data, properties and
methods from outside the world oroutside of the
class scope and exposing only necessary thing.
Encapsulation complements Abstraction.
Abstraction displays only important featuresof a
class and Encapsulation hides unwanted data or
private data from outside of aclass.
Encapsulation can be described as a protective
barrier that prevents the code and data from
being randomly accessed by other code defined
outside the class.

Benefits of Encapsulation
The fields of a class can be made read-only
or write-only.
A class can have total control over what is
stored in its fields.
The users of a class do not know how the
class stores its data. A class can change the
data type of a field and users of the class do
not need to change any of their code.

Access Modifiers
public: Access is not restricted.
protected: Access is limited to the
containing class or types derived from the
containing class.
Internal: Access is limited to the current
assembly.
private: Access is limited to the containing
type.

Property
Properties provide the opportunity to
protect a field in a class by reading and
writing to it through the property.
In other languages, this is often
accomplished by programs implementing
specialized getter and setter methods.
C# properties enable this type of protection
while also letting you access the property
just like it was a field.

Traditional Encapsulation
Without Properties

Encapsulating Type State with


Properties

Creating Read-Only Properties

Creating a Write-Only Property

Creating Auto-Implemented
Properties

Composition
Also known as has-a relationship
It allows an object to be composed of other
objects
Example: A person is composed of a head
object, a body object, 2 hand objects, etc.

Inheritance

Inheritance allows child classes to inherit


the characteristics of an 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

Types of Inheritance

Inheritance terminology

Inheritance Benefits

Inheritance has a lot of benefits

Extensibility
Reusability
Provides abstraction
Eliminates redundant code

Use inheritance for building is-a


relationships
E.g. dog is-a animal (dogs are kind of animals)

Don't use it to build has-a relationship


E.g. dog has-a name (dog is not kind of name)

Inheritance Example

Class Hierarchies

Inheritance leads to a hierarchy of classes


and/or interfaces in an application:

Generalization and
Specialization
The general characteristics are specified
high up in the hierarchy
More specific characteristics are specified
below the hierarchy

Inheritance in .NET

A class can inherit only one base class


E.g. IOException derives from
SystemException and it derives from Exception

A class can implement several interfaces


This is .NETs form of multiple inheritance
E.g. List<T> implements IList<T>,
ICollection<T>, IEnumerable<T>

An interface can implement several interfaces


E.g. IList<T> implements ICollection<T> and
IEnumerable<T>

How to Define Inheritance?

We must specify the name of the base class


after the name of the derived
public class Shape
{...}
public class Circle : Shape
{...}

In the constructor of the derived class we


use the keyword base to invoke the
constructor of the base class
public Circle (int x, int y) : base(x)
{...}

Simple Inheritance
Example
public class Mammal
{
public int Age { get; set; }
public Mammal(int age)
{
this.Age = age;
}
public void Sleep()
{
Console.WriteLine("Shhh! I'm
sleeping!");
}
}

public class Dog : Mammal


{
public string Breed { get; set; }
public Dog(int age, string breed)
: base(age)
{
this.Breed = breed;
}
public void WagTail()
{
Console.WriteLine("Tailwagging...");
}
}

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
}

class Dog : Mammal


{
public string Breed { get; private set; }
// base.Talk() cannot be invoked here (it is
private)
}
class InheritanceAndAccessibility
{
static void Main()
{
Dog joe = new Dog();
Console.WriteLine(joe.Breed);
// joe.Walk() is protected and can not be
invoked
// joe.Talk() is private and can not be invoked
// joe.Name = "Rex"; // Name cannot be accessed
here
// joe.Breed = "Shih Tzu"; // Can't modify
Breed
}
}

Inheritance: Adding
Functionality
Subclasses have all of the data members
and methods of the superclass
Subclasses can add to the superclass

Additional data members


Additional methods

Subclasses are more specific and have more


functionality

Inheritance: Important
Aspects

Structures cannot be inherited

In C# there is no multiple inheritance


Only multiple interfaces can be implemented

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

Inheritance: Important Features

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

The Object class

In C#, all classes are (direct or indirect)


subclasses of the Object class.
It is the root of the inheritance hierarchy in C#
If a class is not declared to inherit from another
then it implicitly inherits from the Object class
It defines a ToString() method which could be
overriden by the subclasses.
Example: From a class named Book

Polymorphism

Polymorphism is the 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 and implemented in the child classes
Declared as abstract or virtual

Polymorphism

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

Polymorphism: How it
works?
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

Virtual Methods
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 CalculateSurface()

Methods that are declared as virtual in a base


class can be overridden using the keyword
override in the derived class

The override modifier


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

Example:
publicclass Shape
{
publicvirtualvoid Draw()
{
Console.WriteLine("Performing base class drawing tasks");
}
}
-----------------------------------------------------class Circle : Shape
{
publicoverridevoid Draw()
{
Console.WriteLine("Drawing a circle");
base.Draw();
}
}

class Program
{
staticvoid Main()
{
Shape shape = new Shape();
Shape circle = new Circle();
shape.Draw();
circle.Draw();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
OUTPUT:
Performing base class drawing tasks
Drawing a circle
Performing base class drawing tasks

Abstract Class

Abstract classes are special classes defined


with the keyword abstract
Mix between class and interface
Partially implemented or fully unimplemented
Not implemented methods are declared abstract
and are left empty
Cannot be instantiated

Child classes should implement abstract


methods or declare them as abstract

When you try to create an instance of the


FourLeggedAnimal class as follows:

FourLeggedAnimal someAnimal = new FourLeggedAnimal();

You will get this fine compiler error:


Cannot create an instance of the abstract class or
interface 'AbstractClasses.FourLeggedAnimal'

Overriding the virtual method

Interface

An interface is defined as a syntactical


contract that all the classes inheriting the
interface should follow.

The interface defines the'what'part of the


syntactical contract and the deriving classes
define the'how part of the syntactical
contract.

Declaring an Interface
interfaceIMyInterface
{
voidMethodToImplement();
}

Example: Advantage of using


Interface

The pug has various


behavior

public class Pug


{
private string name;

public Pug(string n)
{
name = n;
}

public string GetName()


{
return name;
}

public string Bark()


{
return "Arf!";
}

public boolean HasCurlyTail()


{
return true;
}
}

The labrador also


has various
behavior

public class Lab


{
private string name;

public Lab(string n)
{
name = n;
}

public string GetName()


{
return name;
}

public string Bark()


{
return Woof!";
}

public boolean HasCurlyTail()


{
return false;
}
}

We can make some pugs and labs:


Pug pug = new Pug("Spot");
Lab lab = new Lab("Fido");

And we can invoke their behaviors:


pug.Bark()
-> "Arf!"
lab.Bark()
-> "Woof!"
pug.HasCurlyTail()
-> true
lab.HasCurlyTail()
-> false
pug.GetName()
-> "Spot"

Let's say we run a dog kennel and we need to keep track of all
the dogs were housing. We need to store the pugs and
labradors in separate arrays:
public class Kennel
{
Pug[] pugs = new Pug[10];
Lab[] labs = new Lab[10];

public void AddPug(Pug p)


{
...
}

public void AddLab(Lab l)


{
...
}

public void PrintDogs()


{
// Display names of all the dogs
}
}

But this is clearly not optimal. If we want to


house some poodles, too, we have to
change the Kennel definition to add an
array of Poodles. In fact, we need a
separate array for each kind of dog.

Insight:both pugs and labradors (and poodles) are types of


dogs and they have the same set of behaviors. That is, we
can say (for the purposes of this example) that all dogs can
bark, have a name, and may or may not have a curly tail.
We can use an interface to define what all dogs cando, but
leave it up to the specific types of dogs to implement those
particular behaviors.
The interface says "here are the things that all dogs can do"
but doesn't sayhoweach behavior is done.

interface IDog
{
public string Bark();
public string GetName();
public boolean HasCurlyTail();
}

The Pug and Lab classes must slightly be altered


toimplementthe Dog behaviors. We can say
that a Pugisa Dog and a Labisa dog.

public class Pug : Dog


{
// the rest is the same as before
}

public class Lab : Dog


{
// the rest is the same as before
}

Pugs and Labs can still be instantiated as we did before, but


now we also get a new way to do it:

Dog d1 = new Pug("Spot");


Dog d2 = new Lab("Fido");
This says thatd1is not only a Dog, it's specifically a Pug.
Andd2is also a Dog, specifically a Lab.
We can invoke the behaviors and they work as before:
d1.Bark()
-> "Arf!"
d2.Bark()
-> "Woof!"
d1.HasCurlyTail()
-> true
d2.HasCurlyTail()
-> false
d1.GetName()
-> "Spot"

Here's where all the extra work pays off. The Kennel class
become much simpler. We need only one array and
oneaddDogmethod. Both will work with any object thatisa dog;
that is, objects that implement the Dog interface.

public class Kennel


{
Dog[] dogs = new Dog[20];

public void AddDog(Dog d)


{
...
}

public void PrintDogs()


{
// Display names of all the dogs
}
}

Here's how to use it:


Kennel k = new Kennel();
Dog d1 = new Pug("Spot");
Dog d2 = new Lab("Fido");
k.AddDog(d1);
k.AddDog(d2);
k.PrintDogs();

The last statement would display:


Spot
Fido

An interface gives you the ability to specify a


set of behaviors that all classes that
implement the interface will share in
common. Consequently, we can define
variables and collections (such as arrays) that
don't have to know in advance what kind of
specific object they will hold, only that they'll
hold objects that implement the interface.

Another Example:

Jump interface implemented by Man and


Animal. Man is not the same type as Animal.

You might also like