advanced programming using c# · object oriented programming (oop) object oriented programming was...
TRANSCRIPT
Object Oriented Programming (OOP)
Object oriented programming was a paradigm shift
in the way programs were developed.
The basic concepts are grouped around the phrases
MSc Programming - Dr R. Kharel 2
• Object,
• Class,
• Encapsulation,
• Inheritance
• Polymorphism.
• Objects model themselves on real-world things
(e.g. you could imagine a Person object)
and interact with each other.
Classes and Objects
• Class is a blueprint that defines a new data type.
• Contains combination of different attributes to define
something and methods to access them.
• Classes can be instantiated into objects which are self
contained entities.
• Objects are concrete realization or instantiation for the
model specified on class.
• A class is a blueprint from which individual objects are
created.
• When programing in OOP language, it is important to
think of what different entities can be defined as classes.
MSc Programming - Dr R. Kharel 3
Classes and Objects
• For example, in a banking system, Account can be a class
and your and mine account are instance of that class.
• In the university, Student can be a class and each
students instance of Student, i.e. objects
• Lecturer can be a class and I am one instance of it
• Computer is a class and this computer is one instance
• So, any noun is a class
• Classes and Objects model the real world environment
more closely
MSc Programming - Dr R. Kharel 4
MSc Programming - Dr R. Kharel 5
Initial balance £100
Account current balance
£900
John's account Jack's account
Account current balance
£1,304
Account current balance
£432
Account
Jill's account
Class
Individual objects
Defining a Class
class Account {
//attributes are defined here
float minimumBalance;
string accountNumber;
string accountName;
float currentBalance;
//now method goes in here
public void Transaction(float amount){
currentBalance += amount;
}
public void showAll() {
Console.WriteLine(“The account number {0} has £ {1}
balance currently”, accountName,currentBalance);
}
}
MSc Programming - Dr R. Kharel 6
Instantiation of Objects
• The object can be instantiated by using a new() keyword.
• Each new object is given a new identity.
Account jack = new Account();
Account jill = new Account();
• Each new object is given a new identity.
• Each new object can have its own state (by containing its
own data/attributes).
MSc Programming - Dr R. Kharel 7
More on instantiation of objects
Account jack = new Account();
Create a
reference to an
object
Create an object
Assign
reference to
object
A reference is analogous to a pointer in C/C++ -
it refers or points to an object in memory
somewhere.
MSc Programming - Dr R. Kharel 8
class Hello
{
public void Go()
{
Console.WriteLine("Hello World!!! By Object Instantiation");
}
}
class Program
{
static void Main(string[] args)
{
Hello h = new Hello(); // object h of class instantiated
h.Go(); // Go method called
}
}
MSc Programming - Dr R. Kharel 9
Create a new class file in VS, Person.cs
class Person { public int age; public string name; public string address; public double height; public double weight; public string bmiResult; public void CalculateBMI() { //write the program to calculate BMI here and put the result in string bmiResult; bmiResult = "OverWeight"; } public void GetPerson() { Console.WriteLine("I am {0}. \nI am {1} years old. \nMy address is {2}\nAnd I am {3}\n",name,age,address,bmiResult); } }
MSc Programming - Dr R. Kharel 10
The Program.cs contains the Main() and is as follows
class Program { static void Main(string[] args) { Person jack = new Person(); //new object jack of type class Person jack.name = "Jack Smith"; jack.age = 21; jack.address = "Manchester, Chester Street"; jack.height = 165; jack.weight = 75; jack.CalculateBMI(); //method defined inside the class called jack.GetPerson(); Person jill = new Person(); //new object jill of type class Person jill.name = "Jill Young"; jill.age = 22; jill.address = "Manchester Met Uni"; jill.height = 155; jill.weight = 65; jill.CalculateBMI(); //method defined inside the class called jill.GetPerson(); } }
MSc Programming - Dr R. Kharel 11
Access Modifiers and Accessibility Levels
• This defines who has access to attributes or methods. In
the earlier example, things are defined as public, meaning
they can be accessed by anyone and changed.
• e.g. the string bmiResult can be changed outside instead
of calculation, which we really don’t want.
• C# provides access modifiers.
MSc Programming - Dr R. Kharel 13
• So really our Person should be defined like this
class Person
{
private int age;
private string name;
private string address;
private double height;
private double weight;
private string bmiResult;
public void CalculateBMI()
{
//write the program to calculate BMI here and put the result in string bmiResult;
bmiResult = "OverWeight";
}
public void GetPerson()
{
Console.WriteLine("I am {0}. \nI am {1} years old. \nMy address is {2}\nAnd I am {3}\n",name,age,address,bmiResult);
}
}
Default is private if not defined
MSc Programming - Dr R. Kharel 14
• If all the attributes are private, then how to set or read their values then.
• For this we have to define methods (getters and setters)
e.g
public void setAge(int newAge) //this sets the age to newAge
{
age = newAge;
}
public int getAge() //this returns the age
{
return age;
}
If we just want read-only access, then we can only define getters method.
MSc Programming - Dr R. Kharel 15
Built in getters/setters in C# e.g.
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
Property Age is defined and getter and setter are provide in for get {} and set {}
value is a keyword
Convention is to write first letter in uppercase for the property.
MSc Programming - Dr R. Kharel 16
Person jack = new Person();
jack.Age = 21; //calls the setter to set the attribute age to
//the passed value 21
We can’t directly do like this now
jack.age = 21; //because age attribute is private and can’t
// be accessed from outside
int objectAge = jack.Age; // this will now call the getter and
// will assign objectAge with age of
// jack object
MSc Programming - Dr R. Kharel 17
Constructors
• These are special kind of method
• Has the same name as its containing class
• Has to return type
• Is automatically called when a new instance/object is
created, hence the name constructors
• Contains initialization code when each object is created,
like assigning values for attributes, etc
• Can be overloaded
MSc Programming - Dr R. Kharel 18
Constructors (II) class Person
{
private int age;
private string name;
private string address;
public Person()
{
Console.WriteLine(“Constructor called… Object Initialized”);
}
}
So now when the object is initialized the method Person() will be invoked automatically and will display that message.
Person aPerson = new Person();
MSc Programming - Dr R. Kharel 19
Constructors (III) class Person { private int age; private string name; private string address; public Person() { age = 0; name = “undefined”; address = “undefined”; } public Person(theName,theAge,theAddress) { age = theAge; name = theName; address = theAddress; } }
This is overloading constructors and the appropriate constructor will be invoked depending on the parameters passed.
MSc Programming - Dr R. Kharel 20
Constructors (IV)
Person onePerson = new Person(); //calls the first one
Person twoPerson = new Person(“Jack”, 21, “MMU”);
//this calls the second one and sets the attributes with the
passed values
MSc Programming - Dr R. Kharel 21
Destructors
• Are opposite of constructors
• Same name as the containing class but prefixes with the ~ sign.
• Automatically called when the object is about to be destructed
• No return type
class person
{
public person(){
}
~person() //destructor
{
// put resource freeing code here
}
}
MSc Programming - Dr R. Kharel 22
Instance variables, local variables and
variable scope
• One of the powerful features of OO is the
concept of instance variables and local
variables.
• An instance variable is declared outside any
method (usually the top of the class) and can
be seen & used by any method in the class
• A local variable is declared inside a method,
and can be used until the method finishes (this
is its scope or lifetime). E.g.
MSc Programming - Dr R. Kharel 23
class Class1{
private string s="instance string";
private int i = 10;
// a simple method, with no return type, and no parameters
public void Go() {
//Declare a couple of local variables
// These will 'hide' the instance variables
string s = "local string";
int i=5;
Console.WriteLine("local string s is "+s);
Console.WriteLine("local int i is "+i);
// We can still reference the instance variables however, using the
'this'
// object reference
Console.WriteLine("instance string s is "+this.s);
Console.WriteLine("instance int i is "+this.i);
}
}
MSc Programming - Dr R. Kharel 24
static void Main(string[] args) {
Class1 c = new Class1();
c.Go();
Console.Read();
}
MSc Programming - Dr R. Kharel 25
26
Using the ‘this’ reference
• Every object can reference itself by using the keyword
this
• Often used to distinguish between a method’s variables
and the instance variables of an object
MSc Programming - Dr R. Kharel
class person
{
int age;
string name;
public person(int age, string name)
{
this.age = age;
this.name = name;
}
public string getPerson()
{
return “I am ”+ this.name + “\nMy age is”+this.age;
}
}
MSc Programming - Dr R. Kharel 27
Terminologies
MSc Programming - Dr R. Kharel 28
encapsulation. Basically this means protecting the
information (data) within the object.
Inheritance Building on the properties of an existing class.
Very useful when trying to re-use software.
Abstraction.
Treating an entity as a whole, not worrying about the details.
We use abstraction without realising it
Treat a car as a single object without worrying
about the complex mechanics.
polymorphism. This literally means many forms.
A neat way of saving duplication of code.
Private (encapsulated)
data (instance variables)
public methods or operations
Setting data
Retrieving data
Encapsulation - protecting private data
MSc Programming - Dr R. Kharel 29
Return types
Two ways to return values from methods
1. By the return statement
2. As a reference parameter.
E.g. Look at the full example “TestMethods” that follows:
MSc Programming - Dr R. Kharel 30
using System;
class TestMethods {
private string data;
public void Method1() {
data="***Set By Method1***";
}
public void Method2() {
this.Method1();
Console.WriteLine("The data string is "+data);
data="***Set By Method2***";
}
public string GetString() {
return data;
}
static void Main() {
TestMethods t = new TestMethods();
t.Method1();
Console.WriteLine("just called method1, data is now :"+t.GetString());
t.Method2();
Console.WriteLine("just called method2, data is now :"+t.GetString());
}
}
Can be any return type
string, any type of object,
arrays, simple data types
etc etc
Could have written
String s;
s=t.GetString();
Complete example “Testmethods”
MSc Programming - Dr R. Kharel 31
Passing data to a method (and returning
some back again). Data is passed to an object via the parameter list of a
method.
Two types of parameter
1. Value
2. Reference
A copy of the data is made and
passed to the method
A reference that points to the
original object is passed to the
method.
If a change is made, the
object’s state changes
everywhere.
MSc Programming - Dr R. Kharel 32
Parameter lists
• Parameters are passed to methods by order and type, THE NAME IS UNIMPORTANT – see the examples later
• E.g.
double bbb;
char aaa;
int k;
setData(k,aaa,bbb);
……………………………………………….
public void setData(int i, char c, double d)…
Data declaration
Call method setData
Method declaration
MSc Programming - Dr R. Kharel 33
Parameter passing by value
• A COPY of the parameter is passed to the method:
public void ChangePi(double rrr) {
rrr=100.0;
Console.WriteLine("In ChangePi.. rrr is "+rrr);
}
double r=3.14159;
// An example of pass by value
ChangePi(r);
Console.WriteLine("In Main, after changepie, new value is :" + r);
OUTPUT: Prints 100, then 3.14159
rrr has ‘local
scope’
MSc Programming - Dr R. Kharel 34
Pass by reference – changing the original
object.
public void ChangePiByRef(ref double rrr) {
rrr=100.0;
Console.WriteLine("In ChangePiByRef.. rrr is "+rrr);
}
double r=3.14159;
Console.WriteLine("Before the call to ChangePi : "+r);
// An example of call by reference
ChangePiByRef ( ref r );
Console.WriteLine("In Main, new value is :" + r);
With pass by reference, the
ADDRESS of the original object is
passed
Prints 3.14159 then 100,
then 100.
MSc Programming - Dr R. Kharel 35
Another type of reference parameter, the OUTPUT parameter.
For passing new values back from a method
public void ChangePiOutput(out double rrr) {
rrr = 123.4;
Console.WriteLine("In CHangePiOutput, new value is :" + rrr);
}
r=100.0;
ChangePiOutput(out r);
Console.WriteLine("In Main,after ChangePiOutput new value is :" + r);
No real need
to initialise r Prints 123.4
MSc Programming - Dr R. Kharel 36
Local variables, instance variables and the this
reference.
• We need to understand the scope of a
variable or object (i.e. when it exists and
ceases to exist).
• A variable is passed to another object via a
parameter list.
• It becomes a local variable.
• To preserve it, it must be copied to an
instance variable.
MSc Programming - Dr R. Kharel 37
Local variables, instance variables and all
that. E.g.
public class Person {
private int ID;
private string name;
public void setData(string nameIn, int IDIn) {
name = nameIn;
ID = IDIn;
} //etc etc
}
instance or
member
variables
local variables,
with local or
block scope
Notice: local &
instance variables
named differently.
Local variables go out
of scope here;
instance variables
last for the life time
of the object
MSc Programming - Dr R. Kharel 38
Simplifying code using the this reference.
Keyword this is a reference to the object itself...
public class Person {
private int ID;
private string name;
public void setData(string name, int ID) {
this.name = name;
this.ID = ID;
} //etc etc
}
no confusion now
between local and
instance variables
MSc Programming - Dr R. Kharel 39
Static Classes and Static Class Members
• A static class is basically the same as a
non-static class, but there is one difference:
a static class cannot be instantiated.
• cannot use the new keyword to create a
variable of the class type
• the members of a static class is accessed
by using the class name itself.
• Have we seen static keyword before
somewhere??
MSc Programming - Dr R. Kharel 40
Static Classes and Static Class Members
• For example, in the .NET Framework Class Library,
the static System.Math class contains methods that
perform mathematical operations, without any
requirement to store or retrieve data that is unique to
a particular instance of the Math class.
double dub = -3.14;
Console.WriteLine(Math.Abs(dub));
Console.WriteLine(Math.Floor(dub));
Console.WriteLine(Math.Round(Math.Abs(dub)));
// Output:
// 3.14
// -4
// 3
MSc Programming - Dr R. Kharel 41
Main features of a static class:
• Contains only static members
• Cannot be instantiated
• Is sealed - cannot be inherited
• Cannot contain Instance Constructors – but can
have static constructor
Non-static classes should also define a static constructor
if the class contains static members that require non-
trivial initialization.
MSc Programming - Dr R. Kharel 42
Example – Temperature converter
public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
MSc Programming - Dr R. Kharel 43
Example – Temperature converter
MSc Programming - Dr R. Kharel 44
class TestTemperatureConverter { static void Main() { Console.WriteLine("Please select the convertor direction"); Console.WriteLine("1. From Celsius to Fahrenheit."); Console.WriteLine("2. From Fahrenheit to Celsius."); Console.Write(":"); string selection = Console.ReadLine(); double F, C = 0; switch (selection) { case "1": Console.Write("Please enter the Celsius temperature: "); F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine()); Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F); break; case "2": Console.Write("Please enter the Fahrenheit temperature: "); C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine()); Console.WriteLine("Temperature in Celsius: {0:F2}", C); break; default: Console.WriteLine("Please select a convertor."); break; } // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }
Example Output:
Please select the convertor direction
1. From Celsius to Fahrenheit.
2. From Fahrenheit to Celsius.
:2
Please enter the Fahrenheit temperature: 20 Temperature in Celsius: -6.67
Press any key to exit.
MSc Programming - Dr R. Kharel 45
Static Members
• A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created.
• The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.
• more typical to declare a non-static class with some static members, than to declare an entire class as static.
• Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.
MSc Programming - Dr R. Kharel 46
Static Members
public class Automobile {
public static int NumberOfWheels = 4; public static int SizeOfGasTank { get { return 15; } } public static void Drive() { } public static event EventType RunOutOfGas; // Other non-static fields and properties...
} //use Automobile.Drive();
int i = Automobile.NumberOfWheels;
MSc Programming - Dr R. Kharel 47
• What are the advantages/disadvantages of using Static
classes and Static members?
MSc Programming - Dr R. Kharel 48
• What are the advantages/disadvantages of using Static
classes and Static members?
• Does the massive use of static concept takes away the
advantages that OOP offers??
MSc Programming - Dr R. Kharel 49
Few Resources for you to have look at
• “Traffic Simulation: A Case Study for Teaching Object
Oriented Design” – available at
http://www.ccs.neu.edu/home/vkp/Papers/Traffic-
sigcse98.pdf
• Case study of ATM simulation – available at
http://www.math-
cs.gordon.edu/courses/cs211/ATMExample/
• Case study of Address Book Example – available at
http://www.cs.gordon.edu/courses/cs211/AddressBookEx
ample/
MSc Programming - Dr R. Kharel 50