Chapter - 4: OOP With C#
Chapter - 4: OOP With C#
Chapter - 4: OOP With C#
OOP with C#
Objectives
Basic Class in C#
Visibility
Encapsulation
Inheritance
Polymorphism
C# Classes
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;
}
Encapsulation
Inheritance
Polymorphism
Examples
Encapsulation
Inheritance
Polymorphism
Shape
Hexagon
Shape
void Draw( )
has-a Relationship
Hexagon
Draw(
)
Circle
Draw(
)
Car
Radio
9
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
class Class1
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.A = 20;
Console.WriteLine(obj.A);
}
}
}
{
get { return currPay; }
16
Read-Only Fields
"is-a" relationship
"has-a" relationship
SalesPerso
n
Manager
19
22
Multiple Inheritance
Sealed Classes
23
SalesPerso
n
Manager
PTSalesPerso
n
Containment/Delegation
or has-a relationship
Types of Polymorphism
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
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
Same as
pure
virtual
function
of C++
Method Hiding
new Modifier
// The new modifier
using System;
public class MyBaseC
{
public static int x = 55;
public static int y = 22;
}
Output:
100
55
22
33
End of
Chapter 4
34