Object Oriented Programming With C#
Object Oriented Programming With C#
Employee
attributes:
string fullName
int empID
float currPay
Methods
Employee()
Employee(string fullName, int empID, float currPay)
void GiveBonus(float amout)
Void DisplayStats();
Method Overloading
• When a class has a set of identically named members that differ by the
number or type of parameters, the member in question is said to be
overloaded.
Eg:
class Triangle
{
public void Draw( int x, int y, int height, int width);
public void Draw( float x, float y, float height, float width);
public void Draw(Point upperLeft, Point bottomRight);
public Draw (Rect r);
}
• When a class member is overloaded, the return type alone is not unique
enough.
public float GetX();
public int GetX();
Self Reference
• “this” keyword
• This keyword is used whenever the reference is to be made to the
current object.
• Static member functions of a type cannot use “this” keyword.
public Employee(string FullName, int empID, float currPay)
{
this.fullName = FullName;
this.empID = empID;
this.currPay = currPay;
this.empSSN = ssn;
}
• Polymorphism: How does this language let you treat related objects
in a similar way?
– Classical – Base class defines a set of members that can be overridden
by subclass. Eg; Draw
– Ad-hoc – Late binding
Encapsulation
• Black box programming
• An object’s internal data should not be directly
accessible from an object instance.
– public
– private
– protected
– protected internal
• Define the data fields as private
– Define a pair of accessor and mutator methods
– Define a named property
using system;
public class Department
{
private string departname;
// Accessor.
public string GetDepartname()
{
return departname;
}
// Mutator.
public void SetDepartname( string a)
{
departname=a;
}
public static int Main(string[] args)
{
Department d = new Department();
d.SetDepartname("ELECTRONICS");
Console.WriteLine("The Department is :"+d.GetDepartname());
return 0;
}
}
public string Name
{
get { return fullName; }
set { fullName = value;}
}
// Property for the empID.
public int EmpID
{
get {return empID;}
set
{
empID = value;
}
}
// Property for the currPay.
public float Pay
{
get {return currPay;}
set {currPay = value;}
}
class TimePeriod
{
private double seconds;
stan.currPay; //Error
return 0;
}
public class Radio
{
public void TurnOn(bool on)
{
if(on)
Console.WriteLine("Jamming...");
else
Console.WriteLine("Quiet time...");
}
}
public class Car
{
private int currSpeed;
private int maxSpeed;
private string petName;
bool carIsDead;
public Car() {
maxSpeed = 100;
carIsDead = false;
}
public Car(string name, int max, int curr) {
currSpeed = curr;
maxSpeed = max;
petName = name;
carIsDead = false;
}
// A car has-a radio.
private Radio theMusicBox = new Radio();
public void CrankTunes(bool state)
{
// Tell the radio play (or not).
// Delegate request to inner object.
theMusicBox.TurnOn(state);
}
public void SpeedUp(int delta)
{
// If the car is dead, just say so...
if(carIsDead)
{
Console.WriteLine("{0} is out of order....", petName );
}
else // Not dead, speed up. {
currSpeed += delta;
if(currSpeed >= maxSpeed) {
Console.WriteLine("Sorry, {0} has overheated...", petName );
carIsDead = true;
}
else
Console.WriteLine("=> CurrSpeed = {0}", currSpeed); }}
public class CarApp
{
public static int Main(string[] args)
{
// Make a car.
Car c1;
c1 = new Car("SlugBug", 100, 10);
// Speed up.
Console.WriteLine("\n***** Speeding up *****");
for(int i = 0; i < 10; i++)
c1.SpeedUp(20);
// Shut down.
Console.WriteLine("\n***** Turing off radio for SlugBug *****");
c1.CrankTunes(false);
return 0;
} }
• Create a namespace college
public Student(string newName, string newAddress, string newPhone, string newUsn, string newBranch,
Subject mySubject):
base(newName, newAddress, newPhone)
{ this.usn = newUsn;
this.branch = newBranch;
this.subjectsTaken = mySubject;
}
Teacher Name:Seema
Teacher Address:Hebbal
Teacher Phone:080-765676
Teacher Subject Taught:C#
A C# property actually maps to a get_/set_ pair. (The reverse
is not true)
Eg:
public class Employee
{
private string empSSN;
public string SSN
{
get { return empSSN;}
set{ empSSN = value;}
}
//ERROR
public string get_SSN()
{ return empSSN;}
//Usage:
Employee.Company = “Infosys Inc”;
Console.WriteLine(“The folks work at {0}”, Employee.Company);
Static Constructor
• Static constructors can be used to assign values to static data
• This assignment always happens by default.
//Error
Employee brenner = new Employee();
brenner.SSNField = “666-66-666”;
Preventing Inheritance
public sealed class PTSalesPerson : SalesPerson
{
Public PTSalesPerson(string fullName, int empID, float
currPay, string ssn, int numberOfSales)
{
//Logic
}
}
//Error
Public class ReallyPTSalesPerson: PTSalesPerson
Containment and Delegation
(has-a) relationship
• Eg: Car, radio
Nested Type Definitions
public class Car
{
private class Radio
{
public void TurnOn(bool on)
{
if (on)
Console.WriteLine(“Jamming…”);
else
Console.WriteLine(“Quiet Time…”);
}
}
private Radio theMusicBox = new Radio();
}
• Nested type could be public or private (Not true for other types)
• Car$Radio
C# Polymorphic support
public class Employee
{
protected string fullName;
protected int empID;
protected float currPay;
protected string empSSN;
public Employee(string FullName, int empID, float currPay, string ssn)
{
this.fullName = FullName;
this.empID = empID;
this.currPay = currPay;
this.empSSN = ssn;
}
public void GiveBonus(float amount)
{
currPay + = amount;
}
}
public class SalesPerson : Employee
{
protected int numberOfSales;
}
Manager Chucky = new Manager(“Chucky”, 92, 10000, “333-33-3333”, 9000);
Chucky.GiveBonus();
SalesPerson fran= new Manager(“Fran”, 93, 3000, “999-99-9999”, 31);
Chucky.GiveBonus();
public class Employee
{
protected string fullName;
protected int empID;
protected float currPay;
protected string empSSN;
public Employee(string FullName, int empID, float currPay, string ssn)
{
this.fullName = FullName;
this.empID = empID;
this.currPay = currPay;
this.empSSN = ssn;
}
public virtual void GiveBonus(float amount)
{
currPay + = amount;
}
}
public class SalesPerson : Employee
{
protected int numberOfSales;
base.GiveBonus(amount * salesBonus);
}
}
public class Manager : Employee
{
private ulong numberOfOptions;
Shape
Draw()
Hexagon
Circle
Draw()
namespace Shapes
{
public abstract class Shape
{
protected string petName;
// Constructors.
public Shape(){petName = "NoName";}
public Shape(string s)
{
this.petName = s;
}
// Constructors.
public Shape(){petName = "NoName";}
public Shape(string s)
{
this.petName = s;
}
• If the method in the derived class is preceded with the new keyword, the
method is defined as being independent of the method in the base class.
• If the method in the derived class is preceded with the override keyword,
objects of the derived class will call that method rather than the base class
method.
• The base class method can be called from within the derived class using the
base keyword.
• The override, virtual, and new keywords can also be applied to properties,
indexers, and events.
Versioning
public class MyBase
{
public virtual string Meth1()
{
return "MyBase-Meth1";
}
public virtual string Meth2()
{
return "MyBase-Meth2";
}
public virtual string Meth3()
{
return "MyBase-Meth3";
}
}
class MyDerived : MyBase
{
// Overrides the virtual method Meth1 using the override keyword:
public override string Meth1()
{
return "MyDerived-Meth1";
}
// Explicitly hide the virtual method Meth2 using the new keyword
public new string Meth2()
{
return "MyDerived-Meth2";
}
System.Console.WriteLine(mB.Meth1());
System.Console.WriteLine(mB.Meth2());
System.Console.WriteLine(mB.Meth3());
}
Output
MyDerived-Meth1
MyBase-Meth2
MyBase-Meth3
Casting between Types
• Implicit cast operations
• //PTSalesPerson is a SalesPerson
• SalesPerson jill = new PTSalesPerson(“Jill”, 834, 4000, “145-11-1111”, 5);
You cannot treat a base type reference as a derived type without first
performing an explicit cast !
TheMachine.FireThisPerson((Employee)frank);
Determining the Type of Employee
public class TheMachine
{
public static void FireThisPerson(Employee e)
{
if (e is SalesPerson)
{
Console.WriteLine(“Lost a salesperson names {0}”, e.getfullName());
Console.WriteLine(“{0} made {1} sales…”, e.GetFullName,
((SalesPerson)e).NumbSales);
}
if (e is Manager)
{
Console.WriteLine(“Lost a Manager names {0}”, e.getfullName());
Console.WriteLine(“{0} had {1} stock options…”, e.GetFullName,
((Manager)e).NumbOpts);
}
}
}
public class TheMachine
{
public static void FireThisPerson(Employee e)
{
SalesPerson p = e as SalesPerson;
if (p != null)
{
Console.WriteLine(“Lost a salesperson names {0}”, p.getfullName());
Console.WriteLine(“{0} made {1} sales…”, p.getFullName(),
p.NumbSales);
}
else
{
Manager m = e as Manager;
if (m != null)
{
Console.WriteLine(“Lost a Manager names {0}”,
m.getfullName());
Console.WriteLine(“{0} had {1} stock options…”,
m.getFullName(),
m.NumbOpts);
}}}}
Numerical casts
• int x = 30000;
• byte b = (byte) x; //Loss of information, so cast explicitly
• byte b = 30;
• int x = b; //No loss
1. The present population of two countries, namely My Country and
Your Country are 817 million and 1.088 billion respectively. Their
rates of population growth are 2.1% and 1.3% respectively. Write a
C# program that determines the number of years until the
population of My Country exceeds that of your country.