Anda di halaman 1dari 20

United International University

Trimester: Summer 2009


Course:
CSE 6087
Course Title: Advanced Object-oriented Programming
Week 2: Class

Arithmetic Expressions
Similar to C++ or Java.

Data Conversions
In C#, data conversions can occur in three ways:
Assignment conversion
occurs automatically when a value of one type is assigned to a
variable of another
only widening conversions can happen via assignment
Example: aFloatVar = anIntVar
Arithmetic promotion
happens automatically when operators in expressions convert their
operands
Example: aFloatVar / anIntVar
Casting

Casting
Casting is the most powerful, and dangerous, technique for conversion
Both widening and narrowing conversions can be accomplished by explicitly
casting a value
To cast, the type is put in parentheses in front of the value being converted
For example, if total and count are integers, but we want a floating point result
when dividing them, we can cast total:
result = (float) total / count;

Control Statement
if (studentGrade >= 60)
Console.WriteLine (Passed);

UIU Week 2, CSE 6087

1/20

if ( <test> )
<code executed if <test> is true> ;
else
<code executed if <test> is false> ;

Ternary Conditional Operator (?:)


string result;
int numQ;

result = (numQ==1) ? Quarter : Quarters;

While Statement
int product;
product = 2;
while (product <= 1000)
{
product = 2 * product;
}

For loop
'For' loops tend to be used when one needs to maintain an iterator value. Usually, as in the
following example, the first statement initialises the iterator, the condition evaluates it against
an end value, and the second statement changes the iterator value.
for (int a =0; a<5; a++)
{
System.Console.WriteLine(a);

For each loop


When a 'foreach' loop runs, the given variable1 is set in turn to each value exposed by the
object named by variable2. As we have seen previously, such loops can be used to access
array values. So, we could loop through the values of an array in the following way:
int[] a = new int[]{1,2,3};
foreach (int b in a)
System.Console.WriteLine(b);

UIU Week 2, CSE 6087

2/20

The main drawback of 'foreach' loops is that each value extracted (held in the given example
by the variable 'b') is read-only.

Switch statement
switch ( expression )
{
case value1 :
statement-list1
case value2 :
statement-list2
case ...
default :
statement-list
}

Classes
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

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:

UIU Week 2, CSE 6087

3/20

Console.WriteLine ( "Whatever you are, be a good one.


);
method

class

Information provided to the method


(parameters)

dot

User-defined Classes
We can define classes and objects using
a language approach or
a conceptual approach
The language approach deals with syntax .The conceptual approach deals with purpose if
classes and objects
Conceptual Definition
Abstraction
o Abstraction is a concept which facilitates to extract out the essential
information of an object.
o In OOP ( Object Oriented Programming ) , Abstraction facilitates the
easy conceptualization of real world objects into the software program.
o Abstraction lies everywhere! What ever you see, do and live are all
full of abstraction.
o In mathematics, multiplication is a kind of abstraction. The symbol x
is an abstract symbol that can do multiplication of any two elements.
Encapsulation
o Encapsulation is a way of organising data and methods into a structure
by concealing the way the object is implemented, i.e. preventing
access to data by any means other than those specified.
o Encapsulation guarantees the integrity of the data contained in the
object.

UIU Week 2, CSE 6087

4/20

Information Hiding
o purpose of hiding is to make inaccessible certain details that should
not affect other parts of a system.
Hierarchy
o the mapped relationships of sub- and super classes is known as a
hierarchy

Language Definition
Class
o A class is a blueprint or prototype from which objects are created.
Object
o An object is a software bundle of related state and behavior.
o Software objects are often used to model the real-world objects that
you find in everyday life.
o Class: a concept, e.g., the dog concept
o Object - An instance of a concept, e.g., the dog at my home
Inheritance
o Inheritance provides a powerful and natural mechanism for organizing
and structuring your software
o classes inherit state and behavior from their super classes
Interface
o An interface is a contract between a class and the outside world. When
a class implements an interface, it promises to provide the behavior
published by that in interface.
Namespace
o A namespace is for organizing classes and interfaces in a logical
manner.
Placing your code into Namespace makes large software projects easier to
manage.

UIU Week 2, CSE 6087

5/20

Example #1 - A program that uses the Building class.


using System;
class Building {
public int floors;
// number of floors
public int area;
// total square footage of building
public int occupants; // number of occupants
}
// This class declares an object of type Building.
class BuildingDemo {
public static void Main() {
Building house = new Building(); // create a Building object
int areaPP; // area per person
// assign values to fields in house
house.occupants = 4;
house.area = 2500;
house.floors = 2;
// compute the area per person
areaPP = house.area / house.occupants;
Console.WriteLine("house has:\n " +
house.floors + " floors\n " +
house.occupants + " occupants\n " +
house.area + " total area\n " +
areaPP + " area per person");
}
}

Example #2 How to add method to class


using System;
class Building {
public int floors;
// number of floors
public int area;
// total square footage of building
public int occupants; // number of occupants
// Display the area per person.
public void areaPerPerson() {
Console.WriteLine(" " + area / occupants +
" area per person");
}
}
// Use the areaPerPerson() method.
class BuildingDemo {
public static void Main() {
Building house = new Building();
Building office = new Building();

UIU Week 2, CSE 6087

6/20

// assign values to fields in house


house.occupants = 4;
house.area = 2500;
house.floors = 2;
// assign values to fields in office
office.occupants = 25;
office.area = 4200;
office.floors = 3;

Console.WriteLine("house has:\n " +


house.floors + " floors\n " +
house.occupants + " occupants\n
house.area + " total area");
house.areaPerPerson();

" +

Console.WriteLine();
Console.WriteLine("office has:\n " +
office.floors + " floors\n " +
office.occupants + " occupants\n
office.area + " total area");
office.areaPerPerson();

" +

}
}

Class Construction

Building an object from class is achieved via constructor


Typically you will use a constructor to give initial values to the instance variables
defined by the class.
All classes have constructors. If you do not define constructors then C# provides
default constructor.

Example#1 - A simple constructor


using System;
class MyClass {
public int x;
public MyClass() {
x = 10;
}
}

UIU Week 2, CSE 6087

7/20

class ConsDemo {
public static void Main() {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
Console.WriteLine(t1.x + " " + t2.x);
}
}
Example #2-A parameterized constructor.
using System;
class MyClass {
public int x;
public MyClass(int i) {
x = i;
}
}
class ParmConsDemo {
public static void Main() {
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(88);
Console.WriteLine(t1.x + " " + t2.x);
}
}

Calling a Method

Each time a method is called, the actual arguments in the invocation are
copied into the formal arguments

int

num = SquareSum (2, 3);

static int SquareSum (int num1, int num2)


{
int sum = num1 + num2;
return sum * sum;
}

UIU Week 2, CSE 6087

8/20

Creating and Accessing Objects

We use the new operator to create an object

Random myRandom;
myRandom = new Random();

This calls the Random constructor, which is


a special method that sets up the object

Creating an object is called instantiation

object is an instance of a particular class An

To call a method on an object, we use the variable (not the class), e.g.,
Random generator1 = new Random();
int num = generate1.Next();

Destructor

In C# we usually do not use destructor. So who has the control over the
destructor (in C#)? it's the .Net frameworks Garbage Collector (GC).
It is possible to define a method that will be called prior to an objects final
destruction by garbage collector. This method is called destructor.

Example #1 - Demonstrate a destructor.


using System;
class Destruct {
public int x;
public Destruct(int i) {
x = i;
}
// called when object is recycled
~Destruct() {
Console.WriteLine("Destructing " + x);
}
// generates an object that is immediately destroyed
public void generator(int i) {
Destruct o = new Destruct(i);

UIU Week 2, CSE 6087

9/20

}
}
class DestructDemo {
public static void Main() {
int count;
Destruct ob = new Destruct(0);
/* Now, generate a large number of objects. At
some point, garbage collection will occur.
Note: you might need to increase the number
of objects generated in order to force
garbage collection. */
for(count=1; count < 100000; count++)
ob.generator(count);
Console.WriteLine("Done");
}
}

Method Overloading

Method overloading is the process of using the same method name for
multiple methods
Usually perform the same task on different data types
The following lines use the WriteLine method for different data types:
Console.WriteLine ("The total is:");
double total = 0;
Console.WriteLine (total);

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

UIU Week 2, CSE 6087

10/20

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-byreference

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

Example: ref

Before calling the function ref parameter must be initialized e.g., x=8. If x is not
initialized then you can not call Foo.

static void Foo( ref int p ) {++p;}


static void Main ( string[] args )
{
int x = 8;
Foo( ref x ); // x is ref
Console.WriteLine( x );
}

UIU Week 2, CSE 6087

11/20

Example: out

Out parameter does not need to initialized before calling. They get the values after
the call.

static void Split( int timeLate,


out int days,
out int hours,
out minutes )
{
days = timeLate / 10000;
hours = (timeLate / 100) % 100;
minutes = timeLate % 100;
}
static void Main ( string[] args )
{
int d, h, m;
Split( 12345, out d, out h, out m );
Console.WriteLine( {0}d {1}h {2}m, d, h, m );
}

Example #1
// Swap two values.
using System;
class Swap {
// This method now changes its arguments.
public void swap(ref int a, ref int b) {
int t;
t = a;
a = b;
b = t;
}
}
class SwapDemo {
public static void Main() {
Swap ob = new Swap();
int x = 10, y = 20;
Console.WriteLine("x and y before call: " + x + " " + y);
ob.swap(ref x, ref y);

UIU Week 2, CSE 6087

12/20

Console.WriteLine("x and y after call: " + x + " " + y);


}
}

Example #2
// Swap two references.
using System;
class RefSwap {
int a, b;
public RefSwap(int i, int j) {
a = i;
b = j;
}
public void show() {
Console.WriteLine("a: {0}, b: {1}", a, b);
}
// This method changes its arguments.
public void swap(ref RefSwap ob1, ref RefSwap ob2) {
RefSwap t;
t = ob1;
ob1 = ob2;
ob2 = t;
}
}
class RefSwapDemo {
public static void Main() {
RefSwap x = new RefSwap(1, 2);
RefSwap y = new RefSwap(3, 4);
Console.Write("x before call: ");
x.show();
Console.Write("y before call: ");
y.show();
Console.WriteLine();
// exchange the objects to which x and y refer
x.swap(ref x, ref y);
Console.Write("x after call: ");
x.show();
Console.Write("y after call: ");
y.show();
}
}

UIU Week 2, CSE 6087

13/20

Params

Any number of parameters we can pass to a method when params are used.

Exampl #1
// Demonstrate params.
using System;
class Min {
public int minVal(params int[] nums) {
int m;
if(nums.Length == 0) {
Console.WriteLine("Error: no arguments.");
return 0;
}
m = nums[0];
for(int i=1; i < nums.Length; i++)
if(nums[i] < m) m = nums[i];
return m;
}
}
class ParamsDemo {
public static void Main() {
Min ob = new Min();
int min;
int a = 10, b = 20;
// call with two values
min = ob.minVal(a, b);
Console.WriteLine("Minimum is " + min);
// call with 3 values
min = ob.minVal(a, b, -1);
Console.WriteLine("Minimum is " + min);
// can call with an int array, too
int[] args = { 45, 67, 34, 9, 112, 8 };
min = ob.minVal(args);
Console.WriteLine("Minimum is " + min);
}
}

UIU Week 2, CSE 6087

14/20

Object Return from a method


Example #1
using System;
class Rect {
int width;
int height;
public Rect(int w, int h) {
width = w;
height = h;
}
public int area() {
return width * height;
}
public void show() {
Console.WriteLine(width + " " + height);
}
/* Return a rectangle that is a specified
factor larger than the invoking rectangle. */
public Rect enlarge(int factor) {
return new Rect(width * factor, height * factor);
}
}
class RetObj {
public static void Main() {
Rect r1 = new Rect(4, 5);
Console.Write("Dimensions of r1: ");
r1.show();
Console.WriteLine("Area of r1: " + r1.area());
Console.WriteLine();
// create a rectangle that is twice as big as r1
Rect r2 = r1.enlarge(2);
Console.Write("Dimensions of r2: ");
r2.show();
Console.WriteLine("Area of r2 " + r2.area());
}
}

UIU Week 2, CSE 6087

15/20

Return an Array
Example #1
using System;
class Factor {
/* Return an array containing the factors of num.
On return, numfactors will contain the number of
factors found. */
public int[] findfactors(int num, out int numfactors) {
int[] facts = new int[80]; // size of 80 is arbitrary
int i, j;
// find factors and put them in the facts array
for(i=2, j=0; i < num/2 + 1; i++)
if( (num%i)==0 ) {
facts[j] = i;
j++;
}
numfactors = j;
return facts;
}
}
class FindFactors {
public static void Main() {
Factor f = new Factor();
int numfactors;
int[] factors;
factors = f.findfactors(1000, out numfactors);
Console.WriteLine("Factors for 1000 are: ");
for(int i=0; i < numfactors; i++)
Console.Write(factors[i] + " ");
Console.WriteLine();
}
}

UIU Week 2, CSE 6087

16/20

Public Vs Private access for class members


Example #1
// Public vs private access.
using System;
class MyClass {
private int alpha; // private access explicitly specified
int beta;
// private access by default
public int gamma; // public access
/* Methods to access alpha and beta. It is OK for a
member of a class to access a private member
of the same class.
*/
public void setAlpha(int a) {
alpha = a;
}
public int getAlpha() {
return alpha;
}
public void setBeta(int a) {
beta = a;
}
public int getBeta() {
return beta;
}
}
class AccessDemo {
public static void Main() {
MyClass ob = new MyClass();
/* Access to alpha and beta is allowed only
through methods. */
ob.setAlpha(-99);
ob.setBeta(19);
Console.WriteLine("ob.alpha is " + ob.getAlpha());
Console.WriteLine("ob.beta is " + ob.getBeta());

//
//

// You cannot access alpha or beta like this:


ob.alpha = 10; // Wrong! alpha is private!
ob.beta = 9;
// Wrong! beta is private!
// It is OK to directly access gamma because it is public.
ob.gamma = 99;
}

UIU Week 2, CSE 6087

17/20

Read only Field


The readonly keyword is a modifier that you can use on fields. When a field declaration
includes a readonly modifier, assignments to the fields introduced by the declaration can
only occur as part of the declaration or in a constructor in the same class.

public readonly int y = 5;

// cs_readonly_keyword.cs
// Readonly fields
using System;
public class ReadOnlyTest
{
class MyClass
{
public int x;
public readonly int y = 25; // Initialize a readonly field
public readonly int z;
public MyClass()
{
z = 24;

// Initialize a readonly instance field

}
public MyClass(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
}
public static void Main()
{
MyClass p1= new MyClass(11, 21, 32);

// OK

Console.WriteLine("p1: x={0}, y={1}, z={2}" , p1.x, p1.y, p1.z);


MyClass p2 = new MyClass();
p2.x = 55;

// OK

Console.WriteLine("p2: x={0}, y={1}, z={2}" , p2.x, p2.y, p2.z);


}

UIU Week 2, CSE 6087

18/20

Output
p1: x=11, y=21, z=32
p2: x=55, y=25, z=24
----------------------

if you use p2.y = 66;

// Error

Activities
Problem #1;)
Write a c# class of rectangle which has property height and width and method area();
Hints:)
using System;
class Rect {
public int width;
public int height;
public Rect(int w, int h) {
this.width = w;
this.height = h;
}
public int area() {
return this.width * this.height;
}
}
class UseRect {
public static void Main() {
Rect r1 = new Rect(4, 5);
Rect r2 = new Rect(7, 9);
Console.WriteLine("Area of r1: " + r1.area());
Console.WriteLine("Area of r2: " + r2.area());
}
}

Problem 2:)
Write a program in VS which reads principal and interest and shows the compound
interest on a message box.
Hint:
// Interest.cs
2
// Calculating compound interest, using MessageBox and Pow.

UIU Week 2, CSE 6087

19/20

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
27
28
28
29
30
31

using System;
using System.Windows.Forms;
class Interest
{
static void Main( string[] args )
{
decimal amount, principal = ( decimal ) 1000.00;
double rate = .05;
string output;
output = "Year\tAmount on deposit\n";
for ( int year = 1; year <= 10; year++ )
{
amount = principal *
( decimal ) Math.Pow( 1.0 + rate, year );
output += year + "\t" +
String.Format( "{0:C}", amount ) + "\n";
}
MessageBox.Show( output,
"Compound Interest",
MessageBoxButtons.OK,
MessageBoxIcon.Information );
} // end method Main
} // end class Interest

Problem 3:)
Implement a website which uses HTML controls to record voter information e.g.,
Voter list project where name, age, nationality, district, education etc. could be
entered using this website. Hints: For photo (use your jpeg file), sex {male/female},
district {use list box}, age, education {SSC, HSC, Graduation, Higher Degree etc.)
use check box.
Problem 4:)
Also complete the above using web controls. Add also a calendar control to store
birth date of the voter instead of age.

*************** End of Week 2 **************

UIU Week 2, CSE 6087

20/20

Anda mungkin juga menyukai