Date post: | 20-Jun-2015 |
Category: |
Technology |
Upload: | phanleson |
View: | 269 times |
Download: | 1 times |
ClassesMethods and Properties
Introduction to Classes and Objects
In object-oriented programming terminology, a class is defined as a kind of programmer-defined type
From the natural language definition of the word “class”:Collection of members that share certain attributes and functionalityLikewise classes in object-oriented programming
In object oriented programming languages (like C#, Java) classes are used to combine everything for a concept (like date)Data (state / attributes) (e.g. date day, month, year)Methods (behavior / tasks) (e.g. display date, increment date)
An Overview of Object Oriented (OO) Programming
An example without OO programming - Calendar display program needs several utility functions/methods
leap year check day of week function
…
day
day of week
month
MonthName leap year
yearData
Functions
. . .
Is this structure complex? • for some yes, for some no
An Overview of Object Oriented (OO) ProgrammingOO version - Calendar display program
Date concept is developed as a class data and methods combined together from the point of view of
programmer
Did you like this? • for some yes, for some no
OO approach is more suitable for a human being• human cognition is mostly based on objects
Data (day, month, year)
MethodsDay of the weekMonth name…
Introduction to Classes and ObjectsWe define variables of types (like int, double). Similarly,
we define objects of classesan object is a member of a class
Why classes and objects? In other words, why object-oriented programming?It gives programmers the ability to write programs using off-the-
shelf components without dealing with the complexity of those components
Saves time and effortObjects are how real-world entities are represented.
You may design and implement, and later use your own classes, but we will start with using other-programmers-defined classesExamples: we used the Console classthis is what a programmer generally does
How to Use Classes?The behavior of a class is defined by its
methods by which objects of that class are manipulated
You should know about the methods and what they doname of the methodparameters and parameter typesreturn typefunctionality
You don’t need to know how the method is implementedanalogy: you can add two int variables using +, but you
don’t need to know how computer really addsmore analogy: you can drive cars, but you don’t need to
know how the fuel injection works
The class Dice Computer simulated dice
not real dice, but have the same functionality random number between 1 and “number of sides”
in this class, we can have dice objects with any number of sides
State number of sides roll count
Methods
Dice(int sides) // constructor – constructs a die with given number of sides
int Roll() // return the random rollint NumSides() // how many sides int NumRolls() // # of times this die rolled
Dice objects will work as pseudo-random number generator Random class from .NET library
Using the class Dice
Console.WriteLine("Rolling {0} sided die.", cube.NumSides());
Console.WriteLine(cube.Roll());
Console.WriteLine(cube.Roll());
Console.WriteLine("Rolled {0} times.", cube.NumRolls());
methods
Dice cube = new Dice(6); // construct six-sided die
Dice dodeca = new Dice(12);// construct twelve-sided die
See UseDice.cs for full program
constructor
State and BehaviorBehavior of a class is what a class does
described in verbs babies eat, cry dice are rolled
In OO programming terminology, behavior is defined by public methodsfor Dice class, methods are the Dice constructor, NumRolls(), NumSides() and Roll()
State of a class depends on physical propertiescars have four wheels, different colorsdice have a number of sidesIn OO programming, State is defined by private data
also called member data, instance variables, or data fields for Dice class, mySides and myRollCount (see Dice.cs)
ObjectsAn object is an instance of a class
When created, in memory a set of private data members are allocated and initialized according to the constructor method In other words, each object has a different state
However, objects share method implementationsThe same function name is used on all objects of the same
class
When a method is called on an object, that object’s private data members are accessed and/or modified
Anatomy of the Dice classThe class Dice
Objects: 6-sided dice, 32-sided dice, one-sided diceMethods: Roll(), NumSides(), NumRolls()
A Dice object has state and behaviorEach object has its own state, just like each int has its own
value Number of times rolled, number of sides
All objects in a class share method implementations, but access their own stateHow to respond to NumRolls()? Return my own # of rolls
What to know?Client programmer (programmer who uses the classes) needs
to know the interfacepublic methods and constructors
parameters, how they behavedoes not need to know private datadoes not need to know how the methods are implemented
From interface to use, the class Dice
static void Main(string[] args) { Dice cube = new Dice(6); Dice dodeca = new Dice(12);
Console.WriteLine(cube.Roll());
Objects constructed
0
myRollCount mySides
6
cube
0
myRollCount mySides
12
dodeca
Method invoked
1
myRollCount mySides
6
cube
Let’s look at the Dice.csDefinition and implementation of the Dice class
Understanding Class Implementations
Private data members are global such that they are accessible by all class member functionse.g. in the implementation of Roll function, mySides and myRollCount are not defined, but used
Understanding Class Implementations
Constructors should assign values to each instance variablethis is what construction isnot a rule, but a general programming style
All data should be privateProvide propertied or methods as needed
Random class Objects of class Random can produce random byte, int and double
values. Method Next of class Random generates a random int value. The values returned by Next are actually pseudorandom numbers—a
sequence of values produced by a complex mathematical calculation. The calculation uses the current time of day to seed the random-
number generator. If you provide Next with two int arguments, it returns a value from the
first argument’s value up to, but not including, the second argument’s value.
The calculation that produces the pseudorandom numbers uses the time of day as a seed value to change the sequence’s starting point.
You can pass a seed value to the Random object’s constructor. Given the same seed value, the Random object will produce the same
sequence of random numbers.
Access Modifiersclass Dice
{
private int myRollCount; // # times die rolled
private int mySides; // # sides on die
public Dice(int sides){}
public int Roll(){}
}
Default is private. (if there is no access modifier)
Access modifierspublic
Methods and Constructors as seen by programmerProgrammer can use the methods and properties defined in the
public section onlyprivate
Mostly the data part of the class Necessary for internal implementation of classNot accessible by programmer
protectedwe will see this in inheritance
internalAccessible only by methods in the defining assembly
protected internalwe will see this in inheritance
Member Data (instance variables)class Dice
{
private int myRollCount;
private int mySides;
}
Will the following code compile? Dice cube = new Dice(6);
Console.WriteLine("Number of sides: {0}",
cube.mySides);
How to fix this?Console.WriteLine("Number of sides: {0}",
cube.NumSides());
Hiding data (encapsulation): why? you can drive cars, but you don’t need to know how the fuel injection works when the car’s fuel injection changes, you can still drive that new car
Properties private int myRollCount; // # times die rolled
// property to get and set the number of sides
public int NumRolls
{
get
{
return myRollCount;
} // end get
set
{
myRollCount = value;
} // end set
} // end property NumRolls
Does get makes sense? How about set?
Properties private int mySides; // # sides on die// property to get and set the number of sides
public int NumSides
{
get
{
return mySides;
} // end get
set
{
mySides = value;
} // end set
} // end property NumSides
Console.WriteLine("Number of sides: {0}", cube.NumSides);
Does get makes sense? How about set?
Autoimplemented Properties
// property to get and set the roll count
public int NumRolls { get; private set; }
// property to get and set the number of sides
public int NumSides { get; set; }
public Dice(int sides)
{
NumRolls = 0;
NumSides = sides;
}
MethodsThe best way to develop and maintain a large application is to
construct it from small, simple pieces divide and conquerMethods allow you to modularize an application by
separating its tasks into reusable units.Reuse the Framework Library, do not reinvent the wheel
Divide your application into meaningful methods such that it is easier to debug and maintain.
Methods == Worker analogy:
Methods syntax access_modifier return_type func_name(parameter list)
{
statement_1;
…
statement_n;
return return_type;
}
(type param1, type2 param2, …, type paramn)
public, private
Examples: public int Roll() public Dice (int sides) public static void Main (string[] args)
Methods syntax (cont’d)There are three ways to return control to the
statement that calls a method.Reaching the end of the method.A return statement without a value.A return statement with a value.
There could be more than one return in a method.At least one return is required in a non-void method.
Method Overloadingvoid DoSomething(int num1, int num2);
void DoSomething(int num1, int num2, int num3);
void DoSomething(float num1, float num2);
void DoSomething(double num1, double num2);
• The compiler distinguishes overloaded methods by their signature—a combination of the method’s name and the number, types and order of its parameters.
Method calls cannot be distinguished by return type compile errorint SquareRoot(int num);double SquareRoot(int num);
Constructor can be overloaded too.
Scope of VariablesThe basic scope rules are as follows:
The scope of a parameter declaration is the body of the method in which the declaration appears.
The scope of a local-variable declaration is from the point at which the declaration appears to the end of the block containing the declaration.
The scope of a non-static method, property or field of a class is the entire body of the class.
If a local variable or parameter in a method has the same name as a field, the field is hidden until the block terminates
Let’s see an example: scope.cs
Static Methodspublic class ScopeTest
{
public static void Main(string[] args)
…
}
public static class Math
{
…
public static int Max(int val1, int val2);
public static int Min(int val1, int val2);
…
} You do not need to create an object in memory to use the method, you
simply use the class’s name to call the method Other methods of the class cannot be called from a static method, only
static methods can be called from other static methods
Math class example (maximum3.cs)
Let’s write a program that finds the maximum of 3 numbersRandomly generate the numbersThen let’s use the Math class to find the maximum