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

Chapter - 4: OOP With C#

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

Chapter - 4

OOP with C#

Objectives

Basic Class in C#
Visibility
Encapsulation

Inheritance

Accessor (get) and Mutator (set)


Named Property
Sealed classes

Polymorphism

Abstract Class and Method


2

C# Classes

A Class is a custom User Defined Type


(UDT)
A Class consists of data (attributes) and
functions (methods)
Example: To model a generic
Employee, we can define an Employee
Class

Employee Class
Employee
attributes:
string fullname;
int empID;
float currPay;

methods:
void GiveBonus(float amount);
void DisplayStats();
4

Source Code
using System;
namespace Employee
{
public class Employee
{
// private data
private string fullName;
private int empID;
private float currPay;
// Default ctor.
public Employee(){ }
// Custom ctor
public Employee(string fullName, int empID, float currPay)
{
// Assign internal state data. Note use of 'this' keyword
this.fullName = fullName;
this.empID = empID;
this.currPay = currPay;
}

Source Code (Contd)


// Bump the pay for this emp.
public void GiveBonus(float amount)
{currPay += amount;}
// Show the state
public void DisplayStats()
{
Console.WriteLine("Name: {0}", fullName);
Console.WriteLine("Pay: {0}", currPay);
Console.WriteLine("ID: {0}", empID);
}
public static void Main(string[ ] args)
{
Employee e = new Employee("Joe",111,23987.50F);
e.GiveBonus(200);
e.DisplayStats();
}
}
}

Method Overloading and 'this'

Overloading of Methods is same as C++.


Constructors can be overloaded.
For method resolution, return type alone is not
necessary!
Is the keyword 'this' always necessary?
Yes, if the parameter name and the class member
name are same. Otherwise No!
Static member functions can't use 'this' keyword.
Why?
The keyword 'this' can also be used to force one
constructor to call another during the object creation
Ex: public Employee(string fullName) : this(fullName,
GetEmpId(), currPay) { }
7

Basic OOP Concepts

Encapsulation

Inheritance

Hiding unnecessary implementation details


"is-a" and "has-a" relationship
"is-a" means sub-classes or derived classes
"has-a" means containment or delegation

Polymorphism

It is the ability of the language to treat related


objects the same way
When sub-classes override the behavior defined by
base a class, they are essentially redefining how
they respond to the same message
8

Examples
Encapsulation

DBReader f = new DBReader(); // details are hidden


is-a Relationship
f.Open("@C:\foo.mdf");
// process the database file
Object
f.Close();

Inheritance
Polymorphism

Shape
Hexagon

Shape
void Draw( )
has-a Relationship
Hexagon
Draw(
)

Circle
Draw(
)

Car
Radio
9

More Details: (1) Encapsulation

The main objective of encapsulation is: the


object's instance should be allowed to access
the internal member data directly. It also
provides the integrity of state data. How to do
this?
Using private, public, protected, and
protected internal keywords
To manipulate the private data, C# provides
two methods:

Define traditional accessor and mutator methods


Define a named property
10

Example

Accessor
class Employee
{
private string fullName;
public string GetName() { return fullName; }
..

Mutator
class Employee
{
private string fullName;
public string SetName(string n)
{ fullName = n; }
.

11

Class Properties

You can define a named property to avoid


using two different get and set methods
The property is a single named field which
wraps the private data. These property
names can then be used in Main( ).
Ex: Assume EmpID is the name of the property
public static void Main()
{
Employee e = new Employee();
p.EmpID = 111; // set
Console.WriteLine(e.EmpID); // get
}
12

C# get and set Methods


using System;
namespace get_set
{
class MyClass
{
private int a;
public int A // property
{
get // accessor
{
return a;
}
set // mutator
{
a = value;
}
}
}

class Class1
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.A = 20;
Console.WriteLine(obj.A);
}
}
}

get block accessor


set block mutator
A named property
13

Read-Only and Write-Only Properties

The named property A in the previous slide


was able to read and write. How to restrict the
access of A as R/W?
For Read-Only: simply define a property
without a set block
For write-only: simply define a property
without a get block
Ex:
public float Pay
public float Pay
{

{
get { return currPay; }

set { currPay = value; }


}
14

static: properties and constructors

The static keyword can be used for properties


also
The only difference is that, now these
properties are bound to a class and not to an
instance
Ex: Employee.EmpID = 111;
Can a constructor be declared as static?
Yes, but it is strange! Why? Because,
constructors are executed during object
creation
Static constructors are used to initialize static
data
15

Example static property


public class Employee
{
private static string companyName;
public static string Company
{
get { return companyName; }
set {companyName = value; }
}
}
public static void Main(string[ ] args)
{
Employee.Company = "Microsoft";
Console.WriteLine("The name is {0}", Employee. Company);
}

16

Example static constructor


public class Employee
{
private static string companyName;
static Employee()
{ companyName = "Microsoft"; }
}
public static void Main(string[ ] args)
{
// below statement is not needed
// Employee.Company = "Microsoft";
Console.WriteLine("The name is {0}",
Employee.Company);
}
17

Read-Only Fields

Read-Only properties provide data preservation: keyword


to be used is: "readonly"
Ex: public readonly int rofield;
You can't assign any value to the readonly fields, except in
a constructor
Ex: void SomeMethod()
{ rofield = 123; } // Error
Static readonly fields can also be used. It is useful to
associate many constant values bound to a class.
It may be look similar to 'const' declaration. The difference,
however, is that const is resolved at compile-time and
static readonly is resolved at run-time.
The other context in which it is valid to pass a readonly
field as an out or ref parameter.
18

More Details: (2) Inheritance

Inheritance facilitates code reuse


Inheritance provides dependency
between types
Inheritance comes in two flavors:

"is-a" relationship
"has-a" relationship

Let us start with "is-a" relationship


Employee

SalesPerso
n
Manager
19

Manager Derived Class


using System;
namespace Employee
{
public class Manager : Employee
{
private ulong numberOfOptions;
public ulong NumberOpts
{
get { return numberOfOptions; }
set { numberOfOptions = value; }
}
}
}
20

SalesPerson Derived Class


using System;
namespace Employee
{
public class SalesPerson : Employee
{
private int numerOfSales;
public int NumbSales
{
get { return numerOfSales; }
set { numerOfSales = value; }
}
}
}
21

Base class and Subclass Constructors

A subclass constructor automatically


calls the base class constructor, by
default
Example:
public Manager(string fullName, int empID, float
currPay, ulong numberOfOpts)
: base (fullName, empID, currPay)
{ numberOfOptions = numberOfOpts; }

22

More features of "is-a"

Multiple Inheritance

"protected " Keyword

In C#, a given class can have exactly one direct


base class
It is not permitted to have a single type with one or
more base classes
You know that a private member can't be accessed
by even subclasses
"protected " data or methods can be accessed by
subclasses

Sealed Classes

If you want to design a class that can't be


inherited, then use the keyword: "sealed "
A sealed class cannot also be an abstract class.
It also enables certain run-time optimizations

23

Example Sealed Classes


Employee

SalesPerso
n
Manager

PTSalesPerso
n

Add a subclass PTSalesPerson for


SalesPerson class to have part time sales
people.
Since we can't think of more child classes
under PTSalesPerson, we shall seal it
Sealed classes are most useful for designing
standalone classes. Ex: String class in the
System namespace
Example
public sealed PTSalesPerson : SalesPerson
{ . }
24

Containment/Delegation
or has-a relationship

Let us consider two classes: A Car class and


a Radio class
It is odd to think of Radio is a Car! Instead,
we can say a Car has a Radio
Car is called as Containing Class
Radio is called as Contained Class
To expose the functionality of the inner class
to the outside world requires delegation
Delegation means adding members to the
containing class that make use of the
contained class's functionality (Ex:
theMusicBox.TurnOn(state); )
25

More Details: (3) Polymorphism

Polymorphism is the ability for classes to provide different


implementations of methods that are called by the same
name.
Polymorphism allows a method of a class to be called
without regard to what specific implementation it provides.
For Example, assume that you have added a new method to
Employee class as:
public void GiveBonus(float amount)
{ currPay += amount; }
This method is common for all objects derived from
Employee. However, our objective is to design this to
behave differently for Manager and SalesPerson.
This means that the subclasses should be able to provide
different interfaces to Employee class
Polymorphism is achieved through " virtual " and " override "
keywords
26

Types of Polymorphism

Interface polymorphism - Multiple classes may


implement the same interface, and a single class may
implement one or more interfaces. Interfaces are
essentially definitions of how a class needs to respond.
An interface describes the methods, properties, and
events that a class needs to implement.
Inheritance polymorphism - Multiple classes may
inherit from a single base class. By inheriting, a class
receives all of the methods, properties, and events of
the base class in the same implementation as the base
class.
Polymorphism through abstract classes - Abstract
classes provide elements of both inheritance and
interfaces. An abstract class is a class that cannot be
instantiated itself; it must be inherited.
27

Example
public class Employee
{
public virtual void GiveBonus(float amount)
{ currPay += amount; }

}
public class SalesPerson : Employee
{
public override void GiveBonus(float amount)
{
int salesBonus = 0;
if (numberOfSales > 200)
salesBonus = 1000;
base.GiveBonus(amount + salesBonus);
}
}

Base Claass

You can reuse the base class method by using the keyword base
Alternatively, the subclass can completely redefine without calling
the base class method
28

Abstract Classes

An abstract class cannot be instantiated


directly, and it is a compile-time error to use
the new operator on an abstract class
An abstract class is permitted (but not
required) to contain abstract members
An abstract class cannot be sealed Why?
Ex: If the Employee class is declared as
abstract, the the following stmt. gives an error:
Employee e = new Employee();
What is the need for an abstract class?
Does it look OK if some one says
"I am an Employee"? or "I am a Sales Person"
29

Example
abstract class A
{
public abstract void F();
}
abstract class B: A
{
public void G() {}
}
class C: B
{
public override void F()
{ // actual implementation of F }
}

A
B
C

The abstract class A introduces an abstract method F.


Class B introduces an additional method G, but since it doesn't
provide an implementation of F, B must also be declared abstract.
Class C overrides F and provides an actual implementation. Since
there are no abstract members in C, C is permitted (but not
required) to be non-abstract.
30

Shape Class Design overview


It is more
intelligent
to declare
Draw() as
abstract

public abstract class Shape


{
public virtual void
Draw()
{}
}

Same as
pure
virtual
function
of C++

public class Circle :


Shape

public class Hexagon :


Shape
{
{}
public override void
Draw()
{ ...Draw(),
}
The subclass Circle does not override
whereas
}
Hexagon does
31

Method Hiding

Method hiding is opposite of Method overriding


Assume that Oval is-a type of Circle. Of course you can
define a method Draw() which overrides Draw() of its parent
class and provide its own versioning.
However, if we want to prevent the Oval class from inheriting
any previous logic, use "new" keyword
public class Oval : Circle
{
public Oval(){base.PetName = "Joe";}
// Hide base class impl if they create an Oval.
new public void Draw()
{
Console.WriteLine("Oval with class versioning");
}
}

new keyword breaks the relationship between base


class of abstract Draw() and the derived class version
32

new Modifier
// The new modifier
using System;
public class MyBaseC
{
public static int x = 55;
public static int y = 22;
}

Output:
100
55
22

public class MyDerivedC : MyBaseC


{
new public static int x = 100; // Name hiding
public static void Main( )
{
Console.WriteLine(x); // Display the overlapping value of x:
Console.WriteLine(MyBaseC.x); // Access the hidden value of x:
Console.WriteLine(y); // Display the unhidden member y:
}
}

33

End of
Chapter 4

34

You might also like