Post on 12-Jan-2016
transcript
UNIVERSITY OFSOUTH ASIA
Lecture 5:
By: Md Rezaul Huda Rezacreativereza@yahoo.com
CSE- 629VISUAL PROGRAMMING
WITH INTERNET)
VISUAL PROGRAMMING
Objects and Classes.C# OO Programming
UNIVERSITY of South Asia
3
UNIVERSITY of South Asia
THIS WEEK… Objects and classes The C# class – has both methods and
fields (variables) as members Code generated by Visual Studio Static (class) variables and methods Properties
3
UNIVERSITY of South Asia
4
OBJECTS. REAL WORLD EXAMPLES
Examples of real-world objects:
your pet, your desk, your bicycle (car?)
What do these real-world objects share? Answer: two characteristics
StateBehaviour
4
UNIVERSITY of South Asia
5
OBJECTS. STATES AND BEHAVIOURS
State example:ColourBreedHungry
BehaviourRunningWagging tail Eating
5
UNIVERSITY of South Asia
6
SOFTWARE OBJECT: MYCAR State:
• make: Mercedes• currentSpeed: 50mph• colour: red• currentGear: 4
6
Behaviour: • brake• change gears• accelerate
This particular car is one instance of
a general car
UNIVERSITY of South Asia
7
SOFTWARE OBJECT: MYCAR -CONT
State = fields/variables • Make: Mercedes• currentSpeed: 50mph• colour: red• currentGear: 4
7
Behaviour = methods
• brake• change gears• accelerate
Object variables are formally known as fields (instance variables )
Object methods are formally known as instance methods
UNIVERSITY of South Asia
8
UNIVERSITY of South Asia
CLASSES Definition: A class is a blueprint, or
prototype, that defines the variables and the methods common to all objects of a certain kind.
Example : Class Car
Variables: make, currentSpeed, colour, currentGear
Methods: brake, change gears,accelerate
8
UNIVERSITY of South Asia
9
THE DIFFERENCE BETWEEN OBJECTS AND CLASSESthe term "object" is sometimes used to refer to both classes and instances
Question: You, as an object, would be an instance of what class?
9
Use to make
ObjectsClass (the blueprint)
UNIVERSITY of South Asia
10
UNIVERSITY of South Asia
EXAMPLE OF CLASS
10
public class Car {
string make; int currentSpeed;string colour; int currentGear;
public void Brake() { ….
}public int ChangeGears (int cg){ ….
}public void Accelerate() { ….
} }
Fields
Methods
UNIVERSITY of South Asia
11
UNIVERSITY of South Asia
EXAMPLE OF OBJECTS
11
public class Car {
......}
public partial class Form1 : Form { .... private Car myPorsche;private Car myTractorpublic Form1(){
myPorsche = new Car();myTractor = new Car();
} }
UNIVERSITY of South Asia
12
UNIVERSITY of South Asia
CREATING A CLASS IN VS In Solution Explorer right click on the name of
the project than Add / Class
12
Class Name with cs
extension
UNIVERSITY of South Asia
13
UNIVERSITY of South Asia
ENCAPSULATION A class encapsulates:
Fields (Instance variables) represent the data
Instance methods represent the behavior
The program does not worry how the class works internally
What is special about a class: both data and behavior are presented in one “unit”
The methods and variables that constitute a class are called members of the class
13
UNIVERSITY of South Asia
14
UNIVERSITY of South Asia
CREATING CLASSES IN C# Class declaration
declares the name of the class along with other attributes
Class Body within curly braces { and } declarations for all fields (instance variables) and
static fields (class variables) and implementations for all instance methods
and static methods (class methods)
14
UNIVERSITY of South Asia
15
UNIVERSITY of South Asia
CONSTRUCTORS These are also part of a class definition A constructor is a sort of class method used to
create new instances - objects of the defined by the class
They are defined and used (called) Example of using/calling a constructor:
Form f; f = new Form();
15
class (type)Variable/field
constructor
UNIVERSITY of South Asia
16
UNIVERSITY of South AsiaMORE ON CONSTRUCTORS
Same identifier (name) as the class name
Do not return a value Void is not included Overloading possibleDefault constructor (the “no-args” constructor)No arguments Example: Form() It is defined by default if no other constructors
are defined
16
UNIVERSITY of South Asia
17
UNIVERSITY of South Asia
CONSTRUCTORS 1 has the same name as the class
public Car () {make = “ Mercedes”; currentSpeed = 0;colour = “Red”; currentGear = 0;
}
Note: classes don't have to have constructors. A default constructor is automatically provided by the runtime system, but it doesn't do anything. To perform some initialization, you will have to write some constructors for your class.
17
No arguments in this case No return type
inside: instantiating fields
UNIVERSITY of South Asia
18
UNIVERSITY of South AsiaCREATING AN OBJECT USING CONSTRUCTOR
18
Declaring a constructor
Calling a constructor when an object is
created
public class Car {
string make, colour;int currentSpeed, currentGear;
public Car () {make = “ Mercedes”; currentSpeed = 0;colour = “Red”; currentGear = 0;
}
public void Brake() {… …}public int ChangeGears (int cg){ …. }public void Accelerate() { …. }
}………………
public Car myCar = new Car();
UNIVERSITY of South Asia
19
UNIVERSITY of South Asia
THE MEMBERS OF A TYPICAL CLASS At least one constructor (the default
one) Methods Fields (the data, sometimes called
member variables) Properties (accessed like fields, but
actually methods)
19
class name
fields
methods
UNIVERSITY of South Asia
20
UNIVERSITY of South Asia
class Dog { private string barkSound; private string breed; private string dogSpeech;
public Dog(){barkSound = "Woof!";breed = "cocker spaniel";
}
public string GetSpeech(){dogSpeech = "Hello. I am a " + breed +
". " + barkSound; return dogSpeech; }
public void SetSound(String bS){this.barkSound = bS;
} }
Class declaration
Fields
Constructor
Methods
Class body
Another C# CLASS Example
Class body
20
UNIVERSITY of South Asia
21
UNIVERSITY of South Asia
OVERLOADING CONSTRUCTORS Same as overloading methods
The compiler differentiates constructors based on the number of parameters (arguments) in the list and/or yhe parameters types
A class can have any number of constructors with the same name
21
Arguments list
No arguments
public Dog(){
barkSound = "Woof!";breed = "cocker spaniel";
}
public Dog( string bs, string b ){
barkSound = bs;breed = b;
}
UNIVERSITY of South Asia
22
UNIVERSITY of South Asia
CREATING OBJECTSDeclaring objects of class Dog:
private Dog lady ;
private Dog tramp ;
At this point lady and tramp are declared but not yet instantiated.
We say that such an object has a null value. Objects are instantiated by using the class’
constructor. Both lady and tramp are of type Dog.
Reference type
22
UNIVERSITY of South Asia
23
UNIVERSITY of South Asia
INSTANTIATING THE OBJECTS Instantiate using the keyword new: lady = new Dog();
tramp = new Dog(“woof woof”, “moggy”);
Note: Every time you instantiate a new object from a class, you get a new copy of each of the class's instance variables.
As local variables, inside methods, you can use “var”:var lady = new Dog(); private Dog lady = new Dog();
23
UNIVERSITY of South Asia
24
UNIVERSITY of South Asia
THE DIFFERENCE BETWEEN OBJECTS AND PRIMITIVE VARIABLES
public double a = 31.3public int b = 20
24
Primitive data types, not composed of any other types
Private Dog lady = new Dog(); Object, composed of other types
31.3
20
reference
a:
b:
lady: Woof ! cocker spaniel
barkSound breed
UNIVERSITY of South Asia
25
REFERENCE TYPES AND VALUE TYPE
• Value types: int, short, double, bool….• Reference types : objects that store references to
the actual data, not the value– built-in reference types: • object• string
• To instantiate a reference object in C#, you have to use new keyword.
• In C# we create a reference and then point the reference at an object allocated the heap with the new keyword, like:
Object myobj;myobj = new Object();
25
UNIVERSITY of South Asia
26
OBJECT SHARING Objects get instantiated by a constructor method from
their class. - private Dog lady = new Dog(); - private Dog tramp = new Dog(“woof woof”, “moggy”);
Another way is simply by assigning the value of
another object. - private Dog myDog = lady;
26
lady:
trump:
myDog:
Woof ! cocker spaniel
barkSound breed
woof woof moggy
barkSound breed
UNIVERSITY of South Asia
27
UNIVERSITY of South Asia
IT’S A DOG’S… CLASS!
27
class Dog { string barkSound; string breed;
public Dog(){barkSound = "Woof!";breed = "cocker spaniel";
}
public string GetSpeech(){var dogSpeech = "Hello. I am a " + breed + ". " + barkSound;
return dogSpeech; }
public void SetSound(string barkSound){this.barkSound = barkSound;
} }
I’m a field (instance variable). Each generated Dog Object has a new copy of me.
I am instantiated to “Woof” in the constructor. That means all created Dogs will bark “Woof”
if nobody changes my content.
I’m a “setter” method !I can make it possible for a field to vary over time.
By the way, did you notice THIS ?
I am an instance method.
I am a local variable. I could be declared as a string
UNIVERSITY of South Asia
28
UNIVERSITY of South Asia
SO, WHAT IS THIS ? two different variables with the same name, barkSound !!
28
class Dog {
String ; ….. ….. public void setSound(string ) { = ; } }
barkSound
barkSoundbarkSound barkSoundthis.
defined as a parameterfor a new barking sound
Field for each dog that is instantiated
this is used to refer to the current instance of Dog.
the current value of the instance variable (this.barkSound) is replaced with the new value passed as an argument (barkSound) to setBark.
UNIVERSITY of South Asia
29
UNIVERSITY of South AsiaRELATIONSHIPS BETWEEN CLASSESclass DogChorus {
Dog lady;
Dog buddy;
public DogChorus() {
lady = new Dog();
buddy = new Dog();
buddy.SetSound("Ruff!");
}
public string GetOutput(){
return lady.GetSpeech()+ ”\n” + buddy.GetSpeech();
}
}
29
class Dog { string barkSound, breed;
public Dog(){ barkSound = "Woof!"; breed = "cocker spaniel"; } public string GetSpeech(){ string dogSpeech = "Hi. I’m a" + breed + ". " + barkSound; return dogSpeech; } public void SetSound(string bs){ barkSound = bS; } }
has a
Question: How is encapsulation applied in the Dog class?
UNIVERSITY of South Asia
30
UNIVERSITY of South Asia
class DogChorus { Dog lady; Dog buddy; public DogChorus() { lady = new Dog(); buddy = new Dog(); buddy.SetSound("Ruff!"); } public string GetOutput(){ return lady.GetSpeech()+ ”\n” + buddy.GetSpeech(); }}
public void SetSound(String barkSound){ this.barkSound = barkSound;}
A DOGS … CHORUS!
30
buddy changes its barking characteristic from the default Woof to Ruff. How?
public Dog(){ barkSound = "Woof!"; breed = "cocker spaniel";}
Class Dog - lady instance
“Woof”
Class Dog -buddy instance
“Ruff”
creating an instance of Dog referred to as lady
“Ruff”
UNIVERSITY of South Asia
31
UNIVERSITY of South Asia
31
THIS
31
Within a class, this refers to the current instance of the class. The this keyword can be used to access members from within constructors and instance methods this is often used in constructors:
public Dog ( string barkSound, string breed)
{
this.barkSound = barkSound;
this.breed = breed;
}
UNIVERSITY of South Asia
32
UNIVERSITY of South Asia
MODIFIERS
Appear in method/ constructor headings
variable declarations
the declaration heading for classes and other class members
Indicates how it can be accessed
Types of modifiers
Access (to do with visibility)
Static32
UNIVERSITY of South Asia
33
UNIVERSITY of South Asia
ACCESS MODIFIERS (PROTECTIONLEVELS FOR CLASS MEMBERS) Class members and classes can have one of the
following protection levelspublic – accessible to everyone internal – accessible within the same
assembly/namespaceprivate – accessible only inside classprotected – accessible for descendants –later lecture
Default protection levelsClass members (fields, instance methods) – privateClasses– internal
33
UNIVERSITY of South Asia
34
UNIVERSITY of South Asia
VISIBILITY. PUBLIC OR PRIVATE? Public makes the methods available to other
pieces of program Private: nobody can access the private variables.
34
private string barkSoundprivate string breedprivate string dogSpeechFields (variables)public Dog()constructorpublic string GetSpeech()public void SetSound(
string bs)methods
Dog() constructor
GetSpeech() SetSound(string bs)methods
Class seen by the programmer Object seen by other pieces of program
UNIVERSITY of South Asia
35
UNIVERSITY of South Asia
THE EFFECTS OF PUBLIC AND PRIVATE ACCESSIBILITY
35
violateEncapsulationUnless properties
enforceencapsulation
provide services to clients – for example, otherclasses
support othermethods in theclass
public private
variables
methods
UNIVERSITY of South Asia
36
UNIVERSITY of South AsiaUSING ACCESS MODIFIERS TO IMPLEMENT ENCAPSULATION: DATA FIELDS
As a general rule, no fields should be declared publicAny changes to the object's state (its
fields/variables) should be accomplished by that object's methods
We should make it difficult, if not impossible, for one object to "reach in" and directly alter another object's state
36
UNIVERSITY of South Asia
37
UNIVERSITY of South Asia
GETTERS AND SETTERS instance methods to access and change
values of fields Getter/Accessor
Returns just the current value Standard naming convention → add ”Get” in front
of instance variable name Accessor for noOfSquareYardsis GetNoOfSquareYards( )
Setters/MutatorsNormally includes one parameter Method body → single assignment statement Standard naming convention add ”Set” to the front
of the instance variable identifier Mutator for noOfSquareYardsis SetNoOfSquareYards( )
37
UNIVERSITY of South Asia
38
UNIVERSITY of South Asia
private string breed;
public string GetBreed{
return breed;}
public void SetBreed (string breed){
this.breed = breed; }
EXAMPLES
38
GetterNo parameter.
Return type
Setter.Parameter.
No return type.
UNIVERSITY of South Asia
39
UNIVERSITY of South Asia
IMPLEMENTING DATA ENCAPSULATION USING PROPERTIES
Use C# properties to provide access to data safelyFields(instance variables) should be declared
private, with public properties that allow safe access to them
Public properties allow clients to:Get (obtain the values of) private data
getter (accessor): controls formatting and retrieval of dataSet (assign values to) private data
setter (mutator): ensure that the new value is appropriate for the data member
39
UNIVERSITY of South Asia
40
USING EXISTING PROPERTIES IN VS
Properties in C# give access to fields
Accessing a property is like using a getter method
Changing a property is like using a setter method
Accessing or changing some properties of an object can be done without writing code - directly in Visual Studio by changing the object’s Properties list
Naming in C# for properties
Use the same name as the instance variable ( field), but start with uppercase character
UNIVERSITY of South Asia
41
UNIVERSITY of South AsiaCREATING C# PROPERTIES
A special construct using set and get keywords Automatically created in VS.
41
private string breed;public string Breed{
get { return breed; }set { breed = value;}
}
Matching data type
The value keyword represents the
implied parameter
How could we make this a read-only property?
Note – no parenthesis
()
UNIVERSITY of South Asia
42
UNIVERSITY of South Asia
GENERATE PROPERTIES IN VS USING REFACTOR Right click on the field:
Click Refactor, than Encapsulate field
42
UNIVERSITY of South Asia
43
UNIVERSITY of South Asia
GENERATE PROPERTIES IN VS Leave the name as it comes by default
(good practice)
43
UNIVERSITY of South Asia
44
UNIVERSITY of South Asia
USING PROPERTIES Access through the object (instance of a class)
44
class Dog{private string breed;public string Breed{ get {return breed;} set {breed = value;}}
...}
class DogChorus { Dog tramp; public DogChorus() { tramp = new Dog();
string myBreed = tramp.Breed; tramp.Breed= “mutt”; .... }
UNIVERSITY of South Asia
45
UNIVERSITY of South Asia
THE STATIC MODIFIER
“Static” Indicates that a variable or a method belongs to the class itself rather than to an instance
Methods with the static modifier = class methods (static methods)The Main( ) method must include static in the first line
Example: Suppose that all dogs have 4 legs. You can define a static :
static int dogLegs = 4;All instances (dogs) share this variable and will
have 4 legs. If you define dogLegs as an instance variable each instance
(e.g. lady, tramp) would have its own copy of the variable, and you assign a different value for each dog (using property, constructor,etc)
45
UNIVERSITY of South Asia
46
UNIVERSITY of South AsiaCLASS METHODS (STATIC METHODS)
Class (static) methods can only operate on class (static) variables and cannot access the instance variables defined in the class*.
To specify that a method is a class method, use the static keyword in the method declaration.
46
class Dog { private static int dogLegs; public static int getLegs() { return dogLegs; } public static void setLegs(int dl) { dogLegs= dl; } }
* Note: class methods cannot access instance variables unless the method created an instance of the class first and accesses the variable through it
Static (class) variable
Static (class) method
UNIVERSITY of South Asia
47
UNIVERSITY of South Asia
CLASS (STATIC) METHODS 2 Methods declared with static modifier Can be defined in any class Not associated with an object The class method M in the class C is
invoked using the notation C.M( … )E. g. Dog.GetLegs();
cannot refer to instance variables It can refer to and manipulate class
variables
47
UNIVERSITY of South Asia
48
UNIVERSITY of South Asia
CALLING STATIC METHODS EXAMPLE
double aValue = 78.926;double result1, result2;result1 = Math.Floor(aValue); // result1 = 78result2 = Math.Sqrt(aValue); // result2 = 8.88403061678651MessageBox.Show (“aValue rounded to 2 decimal places”
+ Math.Round(aValue, 2));
48
Call it through the class name, not an instance
Each call returns a value
Round is called through a class. Must be static
A Value rounded to 2 decimal places is 78.93
MessageBox class as a static method Show()
UNIVERSITY of South Asia
49
UNIVERSITY of South Asia
THE MEMBERS OF A TYPICAL CLASS
At least one constructor Methods (functions in other languages) Fields (the data, sometimes called member
variables) Properties (accessed like fields, but actually
methods)
49
class name
fields
methods
properties
UNIVERSITY of South Asia
50
UNIVERSITY of South Asia
RELATIONSHIP BETWEEN C# ELEMENTS
50
UNIVERSITY of South Asia
51
UNIVERSITY of South Asia
WHAT IS A NAMESPACE? Namespaces provide scope for the
classes defined within a group -an “umbrella”
System: most important and frequently used namespace
Each namespace enclosed in curly braces—{ }
Can define your own namespace
51
UNIVERSITY of South Asia
52
UNIVERSITY of South Asia
EXPLORING A SIMPLE APPLICATION
52
using allows us to call classes from other namespaces
What is the namespace for?
What is a class? DO you notice any new word?
Method called. Where is it declared?
Method declared.
Body of the method
UNIVERSITY of South Asia
53
UNIVERSITY of South Asia
.NET 2010 PARTIAL CLASSES
namespace WindowsApplication1
{ public partial class Form1 :
Form { public Form1() { InitializeComponent(); }….. }}
Allows class implementation across more than one file.
This permits breaking down very large classes
Useful if some parts of a class are automatically generated.
53
UNIVERSITY of South Asia
54
UNIVERSITY of South Asia
54
The partial class Form1
Program class • Always in a
windows application
• Automatic generated code.
• Created to keep class Form1 simple
The partial class Form1 (Designer)
UNIVERSITY of South Asia
55
UNIVERSITY of South Asia
55
partial class Form1 (Designer)
Method that creates buttons labels, etc
UNIVERSITY of South Asia
56
UNIVERSITY of South Asia
CLASS PROGRAM
56
Who is Form1() ?
UNIVERSITY of South Asia
57
UNIVERSITY of South Asia
CLASS DIAGRAM FOR THE DOGS’ WORLD
57
Note: the code is available on teachmat
UNIVERSITY of South Asia
58
UNIVERSITY of South Asia
VIEWING THE CLASS DIAGRAM IN VS
In Solution ExplorerRight click on the name
of the namespaceChoose “View class
diagram”
58
UNIVERSITY of South Asia
59
UNIVERSITY of South Asia
GARBAGE COLLECTION 1 The idea of a “dog” does not disappear, but what about any particular
dog? In real life trump would be born, have a life cycle and at some point, die …
In C#, objects are: Created
the new operator – converts a chunk of raw memory to an object
living the object’s methods/properties are called using the dot operator [.] Other references' to the object
Destroyed Only when all the references to the object have disappeared
How do you know when an object is dead? Answer: If nobody can call it - It can not be reached.
From time to time the garbage collector chases all the references in all the objects to find all the live objects.
59
UNIVERSITY of South Asia
60
UNIVERSITY of South Asia
GARBAGE COLLECTION 2 When you initialize a variable using the new
operator, you are in fact reserving some space in the heap memory. The memory is "allocated" for the variable.
When that variable is no longer needed, such as when your program closes, it (the variable) must be removed from memory and the space it was using can be made available to other variables or other programs.
The .NET Framework solves the problem of garbage collection by "cleaning" the memory after you. This is done automatically when necessary so that the
programmer doesn't need to worry about this issue.
60
UNIVERSITY of South Asia
61
UNIVERSITY of South Asia
ANY QUESTION ? ? ?
UNIVERSITY of South Asia
62
UNIVERSITY of South Asia
THANK YOU