Вы находитесь на странице: 1из 20

This week, we will have the OOP paradigm.

The two basic concepts of OOP are classes and object.


Let start with a class.
What is a class?
Class
 A class is a blueprint of an object that contains variables for storing data and functions
to perform operations on the data.
 A class will not occupy any memory space and hence it is only a logical representation of
data.
 It provides a structure for objects or a pattern which we use to describe the nature of
something (some object).

What is an object?
Object
 Objects are the basic run-time entities of an object oriented system. They may
represent a person, a place or any item that the program must handle.
 It is an instance of a class.
Here are some examples of a class and an object:

Class Objects

Fruits orange
apple

banana

Class Objects
Car volvo
audi
suzuki

Class Objects

Person student

manager

teacher
How to create class?

First Step:

Since class is a template to create an object, it is important to define the object’s attributes and
behavior before declaring a class.

Attributes - are the characteristics of the object.

Behavior - are the action to perform by the object.

Here are some examples to fully understand attributes and behavior:

Let define a class Dog

Dog’s attributes - name, breed, age, color

Dog’s behavior – walk, bark, eat

Let’s define a class Mypoint

Mypoint’s attributes – x , y

Mypoint’s behavior – quadrant the point lies, display value of x and y

Second Step:

Now, to declare a class, the keyword “class” is use followed by the class name.

Syntax:

class className{
}

Here are some examples:

class Person{
}

class Car{
}

class Fruits{
}
Third Step:

Create the components of a class.

Four components of a class:

1. Fields - member-variables from a certain type (usually variables that represent object’s
attributes).
2. Constructor – it is used for creating new objects.
3. Properties – this is the way to describe the characteristics of a given class. Usually, the value of
the characteristics is kept in the fields of the object. Similar to the fields, the properties may be
held by certain object or to be shared among the rest of the objects.
4. Methods - it implement the manipulation of the data (usually to implement object’s behavior).

Let’s discuss each component:

First component: Field/s

How to declare a Field

 follow the rules of declaring a variable


 add an access modifier

Now, let’s learn what an access modifier is.

In OOP, one of its feature is Encapsulation.

Encapsulation is defined as the process of enclosing one or more items within a physical or logical
package. Encapsulation is implemented by using access modifier.

Access modifier is used to set the access level/visibility for classes, fields, methods and properties.

Here are the different access modifiers:

Now, let’s go back on field declaration.

Field

 It is a class-level variable that holds a value.


 Field members should have a private access modifier and used with property.
Here are some examples:
private int x;
private int y;
private string name;
private float average;
private char type;

Second component: Constructor:

How to define a constructor

Syntax:

Default constructor - does not have any parameter.

public className( ){
}

Parameterized constructors – have one or more parameters. Also, this technique helps you to assign
initial value to an object at the time of its creation.
public className(parameter/s) {

Here are some examples:


// default constructor
public Mypoint() {

}
//constructor where x and y can have any value
public Mypoint(int x, int y) {

this.x = x;
this.y = y;

//constructor for Dog class


public Dog(string name, int age, string color, string breed) {

this.name = name;
this.age = age;
this.color = color;
this.breed = breed;
}

“this” keyword
 “this” keyword in C# is used to refer to the current instance of the class.
 It is also used to differentiate between the method parameters and class fields if they
both have the same name.
Third component: Properties

Properties

Also, an application of encapsulation feature of OOP.

Property encapsulates a private field. It provides getters (get{}) to retrieve the value of the underlying
field and setters (set{}) to set the value of the underlying field.

How to define a property?

Syntax for setters:


public void setVariableName(parameter){
this.variableName = variableName;
}

Here are some examples:

public void setX(int x){


this.x = x;
}

public void setY(int y) {


this.y = y;
}

Syntax for getters:


public dataType getVariableName(){
return variableName;
}

Here are some examples:

public int getX() {


return x;
}
public int getY() {
return y;
}

Another way of declaring properties:


private int x, y; // field
public int X { //property for x

get{return x;}
set{ x = value;}

public int Y{//property for y

get { return y; }
set { y = value; }
}
The X property is associated with the x field. It is a good practice to use the same name for both the
property and the private field, but with an uppercase first letter.

The get method returns the value of the variable x.

The set method assigns a value to the x variable. The value keyword represents the value we assign to
the property.

How to call a property?

 Invoking or calling a property is actually the process of getting or setting the value.
Syntax:

<property name>();
or

object. <property name>();

Here are some examples:

getX();

setY();

X;

Y;

Last component: Methods

Methods

 It is a block of code which only runs when it is called.


 You can pass data, known as parameters, into a method.
 Methods are used to perform certain actions, and they are also known as functions.

Why use methods?

 To reuse code
 define the code once
 can be use multiple times

How to define a method?

Syntax :

Access Modifier Return Type Method Name(Parameter List) {

Method Body

}
Elements of a Method

Access Modifier − it determines the visibility of a variable or a method from another class.

Return type − A method may return a value. The return type is the data type of the value the method
returns. If the method is not returning any values, then the return type is void.

Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any
other identifier declared in the class.

Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from
a method. The parameter list refers to the type, order, and number of the parameters of a method.
Parameters are optional; that is, a method may contain no parameters.

Method body − this contains the set of instructions needed to complete the required activity.

Here are some examples:

a. method with two parameters (num1 & num2), and int as the return type.

//compute the sum of two numbers


private int computeSum(int num1, int num2) {

int sum;
sum = num1 + num2;
return sum;
}
b. method with no parameter and void as the return type.

//method that will display How are you


public void displayText() {

Console.WriteLine("How are you?");


}

c. method with two parameters (array name arr and the size) and double as the return type.

//method that will compute the average of all odd numbers in an array
private double computeAverageOdd(int[] arr, int size) {

double ave=0;
int c=0,sum=0;
for (int i = 0; i < size;i++ )
{
if (arr[i] % 2 == 1) {

sum += arr[i];
c++;
}

}
if (c != 0)
{
ave = (double)(sum / c);
}
return ave;

How to call a method?

 Invoking or calling a method is actually the process of execution of the method’s code,
placed into its body.

Syntax:
// for void return datatype
<method_name>();

//for other return type (variable data type must match the return data type)
variable = methodname();

//for objects
objectname.<method_name>();
variable = objectname.methodname();

Here are some examples:

// total (since method computeSum has a return value) has a value of 8


int total = computeSum(3,5);

// total (since method computeSum has a return value) has a value of 23


int total = computeSum(20,3);

//directly call the method name since no return value


displayText() // will print the string how are you

// average hold the return value from all the odd numbers of myarray
int [] myarray = new int[10]
double average = computeAverageOdd(myarray,10);

Note: When the return type of the method are data types that hold values except void, method must
have a return statement in the method’s body.
Now, let’s create a class:

In you project, right click your project name in the Solution Explorer.

Example: my project name is Myclass:

After right click, select add then class or (shift + alt + c), as shown below:

After add, a window will pop up same as below. Class C# is selected and the name of the class must be
change (your class name) as highlighted in yellow color.

Change class Class1.cs to Mypoint.cs (my class name as example).


Let’s define a class Mypoint: a point is represented by two coordinates x and y.

Mypoint’s attributes – x , y

Mypoint’s behavior – display value of x and y (you can add more behavior like at what quadrant)

class Mypoint
{
private int x;
private int y;

// default constructor
public Mypoint() {

}
//constructor where x and y can have any value
public Mypoint(int x, int y) {

this.x = x;
this.y = y;

}
//properties (setter and getters)
public void setX(int x)
{
this.x = x;
}
public void setY(int y)
{
this.y = y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}

//methods

//method that will display the value of x and y by calling the properties
public void displayXY() {

Console.WriteLine("The value of x:" + getX() + "\nThe value of y:" +


getY());

Let define a class Dog

Dog’s attributes - name, breed, age, color

Dog’s behavior – walk, bark, eat

Another example of a class

class Dog
{
private string name;
private int age;
private string color;
private string breed;

//default constructor

public Dog(){

}
//constructors with parameters
public Dog(string name, int age, string color, string breed)
{
this.name = name;
this.age = age;
this.color = color;
this.breed = breed;
}

//properties
public void setName(string name)
{
this.name = name;
}
public void setAge(int age)
{
this.age = age;
}

public void setColor(string color)


{
this.color = color;
}

public void setBreed(string breed)


{
this.breed = breed;
}

public string getName() {


return name;
}

public int getAge()


{
return age;
}
public string getColor()
{
return color;
}
public string getBreed()
{
return breed;
}

//method
public void displayDog()
{

Console.WriteLine("The dog's name:" + getName());


Console.WriteLine("The dog's age:" + getAge());
Console.WriteLine("The dog's color:" + getColor());
Console.WriteLine("The dog's breed:" + getBreed());
}

}
Last Step:

After defining a class, let’s learn how to create an instance of a class (objects).

How to create an instance of a class (objects)?

 “new” keyword is use to create an object

Syntax:

className objectName = new constructor();

Here are some examples:

MyPoint p1 = new MyPoint(); // instance of a MyPoint calling the default constructor

MyPoint p2 = new MyPoint(5,15); //instance of a MyPoint calling the Parameterized constructor

Dog d1 = new Dog();

Dog d2 = new Dog(“Coby”,5,”Black”,”Aspin”);

How to call method using instance of a class(objects)

Here are some examples:

p2.displayXY();

d2.displayDog();

Creating instances of a class (objects) and calling methods in the main program
class Program
{
static void Main(string[] args)
{
//declaring variable for objects
Mypoint p1, p2;
Dog d1, d2;

//creating the object p1 using default constructor


p1 = new Mypoint();
// setting the values for x and y of object p1
p1.setX(5);
p1.setY(10);
// display the attributes of object p1
Console.WriteLine("\nObject P1");
p1.displayXY();

Console.WriteLine("\nObject P2");
//creating the object p2 using constructor with parameters
p2 = new Mypoint(7,20);
//getting the value of x and y of object p2
Console.WriteLine("The value of x:" + p2.getX());
Console.WriteLine("The value of y:" + p2.getY());

Console.WriteLine("\nObject d1");
//creating the object d1 using default constructor
d1 = new Dog();
// setting the values for object d1
d1.setName("Coby");
d1.setAge(2);
d1.setColor("white");
d1.setBreed("Aspin");
// display the attributes of object d1
Console.WriteLine("\nObject d1");
d1.displayDog();

Console.ReadKey();

}
}

Output of the class


Using an instance of class in another class

Example:

A straight line is an object connecting two points. Therefore, a line can be represented by two instances
of class Mypoint.

Let’s define a MyLine class

MyLine’s attributes – Mypoint p1, Mypoint p2

MyLine’s behavior –compute distance of two points, slope of a line

Let’s create the class


class MyLine
{
private Mypoint beg, end;

//default constructor
public MyLine()
{

}
//construtor
public MyLine(Mypoint beg, Mypoint end)
{

this.beg = beg;
this.end = end;
}
// no need to have properties for p1 and p2 since it is an instance of a class
//we can access the properties of Mypoint class for p1 and p2
//add property for new fields in the class

//methods

//compute distance of a line


public void displayLine() {

Console.WriteLine("\nCoordinates of First Point:");


beg.displayXY();
Console.WriteLine("\nCoordinates of First Point:");
end.displayXY();

public double computeDistance()


{
double dis = 0;
// p2.getX() and p1.getX() is a statement to access the x coordinates of p2 and p1
// p2.getY() and p1.getY() is a statement to access the y coordinates of p2 and p1
dis = Math.Sqrt(Math.Pow((end.getX() - beg.getX()), 2) + Math.Pow((end.getY()
- beg.getY()), 2));
return dis;
}
public double computeSlope()
{
double slope;

slope = (double)((end.getY() - beg.getY()) / (end.getX() - beg.getX()));


return slope;

class Program
{
static void Main(string[] args)
{
//declaring variable for objects
Mypoint p1, p2;
MyLine l1, l2;

//creating the object p1 using default constructor


p1 = new Mypoint();
// setting the values for x and y of object p1
p1.setX(5);
p1.setY(10);
// display the attributes of object p1
Console.WriteLine("\nObject P1");
p1.displayXY();

Console.WriteLine("\nObject P2");
//creating the object p2 using constructor with parameters
p2 = new Mypoint(7,20);
//getting the value of x and y of object p2
Console.WriteLine("The value of x:" + p2.getX());
Console.WriteLine("The value of y:" + p2.getY());

Console.WriteLine("\nObject L1 has the following coordinates:");


//create an instance of Myline passing two instances(p1,p2 of Mypoint)
l1 = new MyLine(p1,p2);
l1.displayLine();
double d = l1.computeDistance();
double s = l1.computeSlope();
Console.WriteLine("\nL1 Computed values:");
Console.WriteLine("The distance:" + d.ToString("0.00"));
Console.WriteLine("The slope:" + s);

Console.ReadKey();

}
}
Output:

Practice Exercise (Ungraded)

1. The circle has two data members, a Point representing the center of the circle and a float value
representing the radius.

Implement the following methods:


a. Compute the diameter of the circle.
b. Compute the circumference of the circle
c. Compute the area of the circle
2. The Rectangle has two data members; upperLeft and lowerRight points, that represents upper
left and lower right coordinates, respectively.

Implement the following methods:

a. Compute the length of the rectangle


b. Compute the width of the rectangle
c. Compute the area of the rectangle
d. Compute the perimeter of the rectangle
Exercises (graded)

Define a Name class


Name’s attributes: firstname, middlename, lastname
Name’s behavior: display all the attributes of Name’s class

Define a DebitCard class


DebitCard’s attributes: card number, name,balance.
DebitCard’s behavior: float inquireBalance()
//return the balance
float depositCash(float amount)
//increases the balance with amount
boolean withdrawCash(float amount)
// returns true if sufficient amount is available for withdrawal and
decreases the balance by amount
float interest(float rate)
//calculates the interest rate incurred. Assume the parameter rate is
considered as annual interest. Update the balance available.
Display DebitCard attributes

Create instances of class.

Sample Output:

Enter name: <<Juan dela Cruz>>


Enter account number: A101-1125
Enter beginning balance: 1000.00

DEBIT CARD TRANSACTION


[1] Deposit Cash
[2] Withdraw Cash
[3] Inquire Balance
[4] Calculate Interest Rate
[5] Exit

Your choice: 1

Enter amount: 500.50


Enter name: <<Juan dela Cruz>>
Enter account number: A101-1125
Enter beginning balance: 1500.50

DEBIT CARD TRANSACTION


[1] Deposit Cash
[2] Withdraw Cash
[3] Inquire Balance
[4] Calculate Interest Rate
[5] Exit

Your choice: 2

Enter amount: 200.00

Enter name: <<Juan dela Cruz>>


Enter account number: A101-1125
Enter beginning balance: 1300.50

DEBIT CARD TRANSACTION


[1] Deposit Cash
[2] Withdraw Cash
[3] Inquire Balance
[4] Calculate Interest Rate
[5] Exit

Your choice: 2

Enter amount: 1500.00

INSUFFICIENT FUNDS
DEBIT CARD TRANSACTION
[1] Deposit Cash
[2] Withdraw Cash
[3] Inquire Balance
[4] Calculate Interest Rate
[5] Exit

Your choice: 3

Enter name: <<Juan dela Cruz>>


Enter account number: A101-1125
Enter beginning balance: 1300.50

DEBIT CARD TRANSACTION


[1] Deposit Cash
[2] Wihdraw Cash
[3] Inquire Balance
[4] Calculate Interest Rate
[5] Exit

Your choice: 4

Enter rate: 3.5

Interest Incurred: 3.79


Enter name: <<Juan dela Cruz>>
Enter account number: A101-1125
Enter beginning balance: 1304.29

DEBIT CARD TRANSACTION


[1] Deposit Cash
[2] Wihdraw Cash
[3] Inquire Balance
[4] Calculate Interest Rate
[5] Exit

Your choice: 5

Вам также может понравиться