OOP With CSharp

34
1 OOP with C# Chapter - 4

description

PPT

Transcript of OOP With CSharp

Page 1: OOP With CSharp

1

OOP with C#

Chapter - 4

Page 2: OOP With CSharp

2

Objectives Basic Class in C# Visibility Encapsulation

Accessor (get) and Mutator (set) Named Property

Inheritance Sealed classes

Polymorphism Abstract Class and Method

Page 3: OOP With CSharp

3

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

Page 4: OOP With CSharp

4

Employee Class

Employee

attributes:string fullname;int empID;float currPay;

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

Page 5: OOP With CSharp

5

Source Codeusing System;namespace Employee{

public class Employee{

// private dataprivate string fullName;private int empID;private float currPay;// Default ctor.public Employee(){ } // Custom ctorpublic Employee(string fullName, int empID, float currPay){

// Assign internal state data. Note use of 'this' keywordthis.fullName = fullName; this.empID = empID;this.currPay = currPay;

}

Page 6: OOP With CSharp

6

Source Code (Contd…)// Bump the pay for this emp.public void GiveBonus(float amount){currPay += amount;}

// Show the statepublic 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();

}}

}

Page 7: OOP With CSharp

7

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) { }

Page 8: OOP With CSharp

8

Basic OOP Concepts Encapsulation

Hiding unnecessary implementation details Inheritance

"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

Page 9: OOP With CSharp

9

Examples Encapsulation

DBReader f = new DBReader(); // details are hiddenf.Open("@C:\foo.mdf");// process the database file f.Close();

Inheritance Polymorphism

is-a RelationshipObject

Shape

Hexagon

has-a Relationship

Car

Radio

Shapevoid Draw( )

Hexagon CircleDraw(

)Draw(

)

Page 10: OOP With CSharp

10

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

Page 11: OOP With CSharp

11

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; }…………….

}

Page 12: OOP With CSharp

12

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 propertypublic static void Main(){

Employee e = new Employee();p.EmpID = 111; // setConsole.WriteLine(e.EmpID); // get

}

Page 13: OOP With CSharp

13

C# get and set Methodsusing 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

Page 14: OOP With CSharp

14

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; }} }

Page 15: OOP With CSharp

15

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 instanceEx: 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

Page 16: OOP With CSharp

16

Example – static propertypublic 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);

}

Page 17: OOP With CSharp

17

Example – static constructorpublic 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); }

Page 18: OOP With CSharp

18

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.

Page 19: OOP With CSharp

19

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……

EmployeeManager

SalesPerson

Page 20: OOP With CSharp

20

Manager – Derived Classusing System;namespace Employee{

public class Manager : Employee{

private ulong numberOfOptions;public ulong NumberOpts{

get { return numberOfOptions; }set { numberOfOptions = value; }

}}

}

Page 21: OOP With CSharp

21

SalesPerson – Derived Classusing System;namespace Employee{

public class SalesPerson : Employee{

private int numerOfSales;public int NumbSales{

get { return numerOfSales; }set { numerOfSales = value; }

}}

}

Page 22: OOP With CSharp

22

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; }

Page 23: OOP With CSharp

23

More features of "is-a" Multiple Inheritance

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

"protected " Keyword 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

Page 24: OOP With CSharp

24

Example – Sealed Classes

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

Examplepublic sealed PTSalesPerson : SalesPerson{ ………. }

EmployeeManager

SalesPerson

PTSalesPerson

Page 25: OOP With CSharp

25

Containment/Delegationor 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); )

Page 26: OOP With CSharp

26

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

Page 27: OOP With CSharp

27

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.

Page 28: OOP With CSharp

28

Base Claass

Examplepublic 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);

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

the base class method

Page 29: OOP With CSharp

29

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"

Page 30: OOP With CSharp

30

Exampleabstract class A {

public abstract void F(); } abstract class B: A {

public void G() {} } class C: B {

public override void F() { // actual implementation of F }

}

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.

A

B

C

Page 31: OOP With CSharp

31

Shape Class – Design overview

The subclass Circle does not override Draw(), whereas Hexagon does

public abstract class Shape{

public virtual void Draw()

{ … }}

public class Circle : Shape{ … }

public class Hexagon : Shape{

public override void Draw()

{ ... }}

It is more intelligent to declare Draw() as abstract

Same as pure

virtual function of C++

Page 32: OOP With CSharp

32

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" keywordpublic 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

Page 33: OOP With CSharp

33

new Modifier// The new modifierusing System;public class MyBaseC { public static int x = 55; public static int y = 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:

}}

Output: 1005522

Page 34: OOP With CSharp

34

End of Chapter 4