Download - Visula C# Programming Lecture 6
Visual Programming
Methods, Classes, and Objects
2
Classes/Methods
C# Framework Class Library (FCL) defines many classes, e.g., Console MessageBox Int32 Math
The definition of a class includes both methods and data properties: methods, e.g.,
• Console.Write( )• Console.WriteLine( )• Int32.Parse( )
properties, e.g.,• Int32.MinValue• Int32.MaxValue• Math.PI• Math.E
3
Methods
A method should provide a well-defined, easy-to-understand functionality A method takes input (parameters), performs some
actions, and (sometime) returns a value
Example: invoking the WriteLine method of the Console class:
Console.WriteLine ( "Whatever you are, be a good one.“ );
class methodInformation provided to the method
(parameters)dot
4
Example: Math Class Methods
Method Description Example Abs( x ) absolute value of x Abs( 23.7 ) is 23.7
Abs( 0 ) is 0 Abs( -23.7 ) is 23.7
Ceiling( x ) rounds x to the smallest integer not less than x
Ceiling( 9.2 ) is 10.0 Ceiling( -9.8 ) is -9.0
Cos( x ) trigonometric cosine of x (x in radians)
Cos( 0.0 ) is 1.0
Exp( x ) exponential method ex Exp( 1.0 ) is approximately 2.7182818284590451 Exp( 2.0 ) is approximately 7.3890560989306504
Floor( x ) rounds x to the largest integer not greater than x
Floor( 9.2 ) is 9.0 Floor( -9.8 ) is -10.0
Log( x ) natural logarithm of x (base e) Log( 2.7182818284590451 ) is approximately 1.0 Log( 7.3890560989306504 ) is approximately 2.0
Max( x, y ) larger value of x and y (also has versions for float, int and long values)
Max( 2.3, 12.7 ) is 12.7 Max( -2.3, -12.7 ) is -2.3
Min( x, y ) smaller value of x and y (also has versions for float, int and long values)
Min( 2.3, 12.7 ) is 2.3 Min( -2.3, -12.7 ) is -12.7
Pow( x, y ) x raised to power y (xy) Pow( 2.0, 7.0 ) is 128.0 Pow( 9.0, .5 ) is 3.0
Sin( x ) trigonometric sine of x (x in radians)
Sin( 0.0 ) is 0.0
Sqrt( x ) square root of x Sqrt( 900.0 ) is 30.0 Sqrt( 9.0 ) is 3.0
Tan( x ) trigonometric tangent of x (x in radians)
Tan( 0.0 ) is 0.0
Commonly used Math class methods.
5
Methods Provide Abstraction and Reuse
An abstraction hides (or ignores) the right details at the right time
A method is abstract in that we don't really have to think about its internal details in order to use it e.g., we don't have to know how the WriteLine method works in order to invoke it
Why abstraction? Divide and conquer Reuse Easier to understand
6
Method Declaration: Header
A method declaration begins with a method header
methodmethodnamename
returnreturntypetype
parameter listparameter list
The parameter list specifies the typeThe parameter list specifies the typeand name of each parameterand name of each parameter
The name of a parameter in the methodThe name of a parameter in the methoddeclaration is called a declaration is called a formal argumentformal argument
class MyClass { static int SquareSum( int num1, int num2 )
…
propertiesproperties
7
Method Declaration: Body The method header is followed by the method body
static int SquareSum(int num1, int num2){ int sum = num1 + num2; return sum * sum;}
class MyClass{
…
…
}
8
The return Statement
The return type of a method indicates the type of value that the method sends back to the calling location
A method that does not return a value has a void return type
The return statement specifies the value that will be returned
Its expression must conform to the return type
9
Calling a Method Each time a method is called, the actual
arguments in the invocation are copied into the formal arguments
static int SquareSum (int num1, int num2)
{ int sum = num1 + num2; return sum * sum;}
int num = SquareSum (2, 3);
10
Class Methods (a.k.a. Static Methods)
Previously we use class mainly to define related methods together: For example all math related methods are
defined in the Math class The methods we have seen are defined
as static (or class) methods To make a method static, a programmer
applies the static modifier to the method definition
The result of each invocation of a class (static) method is completely determined by the actual
parameters
11
Method Overloading
The following lines use the WriteLine method for different data types:
Console.WriteLine ("The total is:"); double total = 0; Console.WriteLine (total);
Method overloading is the process of using the same method name for multiple methods Usually perform the same task on different data types
Example: The WriteLine method is overloaded: WriteLine (String s) WriteLine (int i) WriteLine (double d) …
12
Method Overloading: Signature The compiler must be able to determine
which version of the method is being invoked
This is by analyzing the parameters, which form the signature of a method The signature includes the number, type,
and order of the parameters The return type of the method is not part of
the signature
13
Method Overloading
double TryMe (int x){ return x + .375;}
Version 1Version 1
double TryMe (int x, double y){ return x*y;}
Version 2Version 2
result = TryMe (25, 4.32)
InvocationInvocation
14
Parameters: Modifying Formal Arguments You can use the formal arguments (parameters) as
variables inside the method Question: If a formal argument is modified inside a
method, will the actual argument be changed?
static int Square ( int x ){ x = x * x; return x;}
static void Main ( string[] args ){ int x = 8; int y = Square( x ); Console.WriteLine ( x );}
15
Parameter Passing
If a modification on the formal argument has no effect on the actual argument, it is call by value
If a modification on the formal argument can change the actual argument, it is call by reference
16
Call-By-Value and Call-By-Reference in C#
Depend on the type of the formal argument
For the simple data types, it is call-by-value
Change to call-by-reference The ref keyword and the out keyword change
a parameter to call-by-reference• If a formal argument is modified in a method, the
value is changed• The ref or out keyword is required in both method
declaration and method call• ref requires that the parameter be initialized before
enter a method while out requires that the parameter be set before return from a method
17
Example: ref
static void Foo( int p ) {++p;}static void Main ( string[] args ){ int x = 8; Foo( x ); // a copy of x is made Console.WriteLine( x );}
static void Foo( ref int p ) {++p;}static void Main ( string[] args ){ int x = 8; Foo( ref x ); // x is ref Console.WriteLine( x );}
18
C# Classes
A C# class plays dual roles: Program module: containing a list of (static)
method declarations and (static) data fields
Design for generating objects• It is the model or pattern from which objects are
created• Supports two techniques which are essence of
object-oriented programming– “data encapsulation” (for abstraction)
– “inheritance” (for code reuse)
19
User-Defined Class
A user-defined class is also called a user-defined type class written by a programmer
A class encapsulates (wrap together) data and methods:
• data members (member variables or instance variables)
• methods that manipulate data members
20
Objects
An object has: state - descriptive characteristics behaviors - what it can do (or be done to it)
For example, consider a coin in a computer game The state of the coin is its current face (head or tail) The behavior of the coin is that it can be flipped
Note the interactions between state and behaviors the behavior of an object might change its state the behavior of an object might depend on its state
21
public int x, y;private char ch;
class MyClass
Defining Classes
Use Project < Add Class to add a new class to your project
A class contains data declarations and method declarations
Data declarationsData declarations
Method declarationsMethod declarations
Member (data/method) Access Modifierspublic : member is accessible outside the classprivate : member is accessible only inside the class definition
22
Data Declarations
You can define two types of variables in a class but not in any method (called class variables) static class variables nonstatic variables are called instance variables
(fields) because each instance (object) of the class has its own copy
class variables can be accessed in all methods of the class
Comparison: Local variables• Variables declared within a method or within a block
statement• Variables declared as local variables can only be
accessed in the method or the block where they are declared
23
Method Declarations
A class can define many types of methods, e.g., Access methods : read or display data
Predicate methods : test the truth of conditions
Constructors• initialize objects of the class• they have the same name as the class
– There may be more than one constructor per class (overloaded constructors)
• can take arguments• they do not return any value
– it has no return type, not even void
24
Creating and Accessing Objects We use the new operator to create an
object Random myRandom;myRandom = new Random();
This calls the This calls the RandomRandom constructorconstructor, which is, which isa special method that sets up the objecta special method that sets up the object
Creating an object is called instantiation An object is an instance of a particular class
To call a method on an object, we use the variable (not the class), e.g.,
Random generator1 = new Random();
int num = generate1.Next();
25
The Dual Roles of C# Classes
Program modules: • a list of (static) method declarations and (static)
data fields• To make a method static, a programmer applies
the static modifier to the method definition• The result of each invocation of a class method is
completely determined by the actual parameters (and static fields of the class)
• To use a static method: ClassName.MethodName(…);
Design for generating objects:• Create an object• Call methods of the object:objectName.MethodName(…);
26
Creating and Accessing Objects We use the new operator to create an
object Random myRandom;myRandom = new Random();
This calls the This calls the RandomRandom constructorconstructor, which is, which isa special method that sets up the objecta special method that sets up the object
Creating an object is called instantiation An object is an instance of a particular class
To call an (instance) method on an object, we use the variable (not the class), e.g.,
Random generator1 = new Random();
int num = generate1.Next();
27
Method Declarations
Access methods : read or display data Predicate methods : test the truth of conditions Constructors
• initialize objects of the class• they have the same name as the class
– There may be more than one constructor per class (overloaded constructors)– Even if the constructor does not explicitly initialize a data member, all data
members are initialized» primitive numeric types are set to 0» boolean types are set to false» reference (class as type) types are set to null
– If a class has no constructor, a default constructor is provided» It has no code and takes no parameters
• they do not return any value– it has no return type, not even void
28
Using Access Modifiers to Implement Encapsulation: Methods Public methods present to the class’s clients a
view of the services that the class provides • public methods are also called service methods
A method created simply to assist service methods is called a support or helper method
• since a support method is not intended to be called by a client, it should not be declared with public accessibility
29
The Effects of Public and Private Accessibility
violateEncapsulation
Unless properties
enforceencapsulation
provide services to clients
support othermethods in the
class
public private
variables
methods
30
Class example
using System;using System.Collections.Generic;using System.Text;
namespace ConsoleApplication3{ class MyClass { public int a,b; public MyClass(int a,int b) { this.a = a; this.b = b; } public void print() { Console.Write("The value is " + a + " and " + b); } }}
using System;using System.Collections.Generic;using System.Text;
namespace ConsoleApplication3{ class Program { static void Main(string[] args) { int first, second; Console.Write("Enter first value"); first = Int32.Parse(Console.ReadLine()); Console.Write("Enter first value"); second = Int32.Parse(Console.ReadLine()); MyClass m = new MyClass(first, second); m.print(); Console.ReadLine(); }}}