Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
106 views

Lesson 1 Introduction To Object Oriented Programming

Object-oriented programming (OOP) breaks programs into smaller, modular objects that have properties and behaviors to simplify development and maintenance. OOP creates classes with properties and methods that define objects. For example, a Dog class could have properties for color and breed, and a method to define barking. Objects are instantiated from classes and can access properties and methods. This allows complex programs to be built from cooperative objects rather than monolithic code.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

Lesson 1 Introduction To Object Oriented Programming

Object-oriented programming (OOP) breaks programs into smaller, modular objects that have properties and behaviors to simplify development and maintenance. OOP creates classes with properties and methods that define objects. For example, a Dog class could have properties for color and breed, and a method to define barking. Objects are instantiated from classes and can access properties and methods. This allows complex programs to be built from cooperative objects rather than monolithic code.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 6

Introduction to Object-Oriented Programming

As computers increase in processing power, the software they execute becomes more complex. This increased complexity comes at a
cost of large programs with huge codebases that can quickly become difficult to understand, maintain and keep bug-free.

Object-oriented programming (OOP) tries to alleviate this problem by creating networks of objects, each like a small software
'machine'. These objects are naturally smaller entities, simplifying the development task of each unit. However, when the objects co-
operate in a system, they become the building blocks of much more complex solution.

Consider the motor car. If a car were designed as a single machine, it would be seen as hugely complex with lots of opportunities for
failure. However, when broken down into its constituent parts, such as wheels, pedals, doors, etc. the individual design items become
simpler. Each part (or object) is created independently, tested carefully and then assembled into the final product.

The car example is analogous to the object-oriented software. Rather than writing a huge program to create, for example, a project
management system, the solution is broken into real-world parts such as project, task, estimate, actual, deliverable, etc. Each of these
can then be developed and tested independently before being combined.

Classes, Objects and Properties

The basic building blocks of object-oriented programming are the class and the object. A class defines the available characteristics and
behavior of a set of similar objects and is defined by a programmer in code. A class is an abstract definition that is made concrete at
run-time when objects based upon the class are instantiated and take on the class’ behavior.

The basic syntax for the creation of a new class in C# is very simple. The keyword ‘class’ followed by the name of the new class is
simply added to the program. This is then followed by a code block surrounded by brace characters {} to which the class’ code will be
added. To demonstrate, let’s check the Dog class example:

namespace OOPExample
{
class Dog
{

}
}

The Dog class is empty in this example. To make it usable, we need to define its properties (something that will describe the class).
The class properties can be defined by declaring class-scoped variables using the private access modifier as can be seen below:

namespace OOPExample
{
class Dog
{
// class properties
private string _color;
private string _breed;
}
}

Here, we declared the properties _color and _breed that will describe the Dog class. However, since the properties are declared as
private, it is not accessible outside the Dog class. We need to define the access modifiers for the two properties. The access modifiers
are declared public in order for it to become accessible outside the Dog class. Let’s check the updated program code below:

namespace OOPExample
{
class Dog
{
// class properties
private string _color;
private string _breed;

// accessor for _color property


public string Color
{
get { return _color; }
set { _color = value; }
}

// accessor for _breed property


public string Breed
{
get { return _breed; }
set { _breed = value; }
}

}
}

Note: The datatype of the access modifiers must match the datatype of the properties they represent.

Our Dog class is now ready for implementation. To test it, we need to create another class (Program in our example) that contains the
Main method:
namespace OOPExample
{
class Program
{
static void Main(string[] args)
1 | Page
{

// object instantiation
Dog dog = new Dog();

// inputs a value to the _breed property


Console.Write("\nEnter dog's breed: ");
dog.Breed = Console.ReadLine();

// inputs a value to the _color property


Console.Write("\nEnter dog's color: ");
dog.Color = Console.ReadLine();

// outputs the value of the _color and _breed properties


Console.Write("\nThe dog is " + dog.Color + ".");
Console.Write("\nThe dog is a " + dog.Breed + ".");

Console.ReadKey();
}
}
}

In this example, we created an object named dog. Since dog is an object of the class Dog, all properties defined inside Dog is
accessible to dog using the notation object.Accessor as can be seen in the commands dog.Color and dog.Breed. You cannot directly
access the properties _color and _breed since they are private to the Dog class. Thus, writing dog._color and dog._breed will result to
an error. Sample output of the program is presented below:

Enter dog’s breed: husky


Enter dog’s color: brown
The dog is brown.
The dog is a husky.

C# also allows creation of auto-implemented properties. Auto-implemented properties will create the class-scoped variables
automatically behind the scenes so there’s no need for you to define these private variables. Applying auto-implemented properties,
the Dog class will be modified similar to the one below:

namespace OOPExample
{
class Dog
{
// class properties
public string Color {get;set;}
public string Breed {get;set;}
}
}

Adding Methods

A method defines the behavior of a class. To illustrate how to define a method, we will modify the Dog class to include a Bark( )
method that will display the string "Au Au" when called. The updated Dog class is presented below:

namespace OOPExample
{
class Dog
{
// class properties
public string Color {get;set;}
public string Breed {get;set;}

// method definition for Bark()


public string Bark()
{
string cry = "Au Au";
return cry;
}
}
}

To call the method, you need to call it using the notation object.MethodName( ) as can be seen in the updated Program class:

namespace OOPExample
{
class Program
{
static void Main(string[] args)
{

// instantiates dog as an object of the class Dog


Dog dog = new Dog();

// inputs a value to the _breed property


Console.Write("\nEnter dog's breed: ");
dog.Breed = Console.ReadLine();

// inputs a value to the _color property


Console.Write("\nEnter dog's color: ");
dog.Color = Console.ReadLine();

// outputs the value of the _color and _breed properties


Console.Write("\nThe dog is " + dog.Color + ".");
Console.Write("\nThe dog is a " + dog.Breed + ".");

// calls the Bark() method


Console.Write("\nThe dog's cry is " + dog.Bark() + ".");
Console.ReadKey();
}
2 | Page
}
}

Sample output of the program is presented below:


Enter dog’s breed: husky
Enter dog’s color: brown
The dog is brown.
The dog is a husky.
The dog’s cry is Au Au.

Example 1: The Circle Class


Circle.cs

namespace OOPExample
{
class Circle
{
// class properties
public string Color { get; set; }
public double Radius { get; set; }

// method definition for ComputeArea()


public double ComputeArea()
{
double area;
const double PI = 3.1416;
area = PI * Radius * Radius;
return area;
}

// method definition for GetDiameter()


public double GetDiameter()
{
double diameter;
diameter = 2* Radius;
return diameter;
}
}
}

Program.cs
namespace OOPExample
{
class Program
{
static void Main(string[] args)
{
// instantiates circle as an object of the class Circle
Circle circle = new Circle();

// assigns values to the properties


Console.Write("\nEnter circle's color: ");
circle.Color = Console.ReadLine();
Console.Write("\nEnter circle's radius: ");
circle.Radius = Convert.ToDouble(Console.ReadLine());

Console.Write("\nThe color of the circle is " + circle.Color + ".");


Console.Write("\nThe radius of the circle is " + circle.Radius + ".");

// calls the methods


Console.Write("\nThe diameter of the circle is " + circle.GetDiameter() + ".");
Console.Write("\nThe area of the circle is " + circle.ComputeArea() + ".");

Console.ReadKey();

}
}
}

Sample Output:

Enter circle’s color: red


Enter circle’s radius: 2.8
The color of the circle is red.
The radius of the circle is 2.8.
The diameter of the circle is 5.6.
The area of the circle is 24.630144.

Example 2: The Employee Class

Employee.cs

namespace OOPExample
{
class Employee
{
// class properties
public string LastName { get; set; }
public string FirstName { get; set; }
public double RatePerHour { get; set; }
// method definition for ComputeSalary()
public double ComputeSalary(int hoursWorked)
{
double salary;
salary = RatePerHour * hoursWorked;
3 | Page
return salary;
}
}
}

Program.cs

namespace OOPExample
{
class Program
{
static void Main(string[] args)
{
int hoursWorked;

// instantiates employee as an object of the class Employee


Employee employee = new Employee();

// assigns values to the properties


Console.Write("\nEnter last name: ");
employee.LastName = Console.ReadLine();
Console.Write("\nEnter first name: ");
employee.FirstName = Console.ReadLine();
Console.Write("\nEnter rate per hour: ");
employee.RatePerHour = Convert.ToDouble(Console.ReadLine());

Console.Write("\nEnter number of hours worked: ");


hoursWorked = Convert.ToInt32(Console.ReadLine());

// displays the values of the properties


Console.Write("\nPayroll Information");
Console.Write("\nName: " + employee.LastName + ", " + employee.FirstName);

// calls the method to compute the salary


Console.Write("\nSalary: " + employee.ComputeSalary(hoursWorked).ToString("0,000"));

Console.ReadKey();
}
}
}

Sample Output:

Enter last name: Reyes


Enter first name: Jessa
Enter rate per hour: 550.50
Enter number of hours worked: 40

Payroll Information
Name: Reyes, Jessa
Salary: 22,020

Example 3: The StringManipulator Class


StringManipulator.cs

namespace OOPExample
{
class StringManipulator
{
// class property
public string Str { get; set; }

// method definition for DisplayAllVowels()


public string DisplayAllVowels()
{
string vowels = "aeiouAEIOU";
string newStr = "";

for(int x = 0; x < Str.Length; x++)


{
for (int y = 0; y < vowels.Length; y++)
{
if (Str[x] == vowels[y])
{
newStr = newStr + Str[x];
break;
}
}
}
return newStr;
}

// method definition for CountVowels()


public int CountVowels(int startingIndex)
{
int counter = 0;
string vowels = "aeiouAEIOU";

if (startingIndex >= 0 && startingIndex < Str.Length)


{
for (int x = startingIndex; x < Str.Length; x++)
{
for (int y = 0; y < vowels.Length; y++)
{
if (Str[x] == vowels[y])
{
counter++;
break;
}
4 | Page
}
}
}
else
return 0;
return counter;
}
}
}

Program.cs

namespace OOPExample
{
class Program
{
static void Main(string[] args)
{
int startingIndex;

// instantiates stringManipulator as an object of the class StringManipulator


StringManipulator stringManipulator = new StringManipulator();

// assigns value to the property


Console.Write("\nEnter a string: ");
stringManipulator.Str = Console.ReadLine();

// calls the methods


Console.Write("\nThe vowels are: " + stringManipulator.DisplayAllVowels());
Console.Write("\nEnter starting index: ");
startingIndex = Convert.ToInt32(Console.ReadLine());
Console.Write("\nThere are " + stringManipulator.CountVowels(startingIndex) + " vowels.");

Console.ReadKey();
}
}
}

Example 4: The Smartphone Class


Smartphone.cs

namespace OOPExample
{
class Smartphone
{
// class properties
public string Model { get; set; }
public double InternalMemory { get; set; }
public double RemainingMemory { get; set; }
public bool isOn { get; set; }

// method definition for TurnOn()


public void TurnOn()
{
if (isOn == false)
{
isOn = true;
Console.Write("\nThe smartphone is now running...");
}
else
Console.Write("\nThe smartphone is already running...");
}

// method definition for TurnOff()


public void TurnOff()
{
if (isOn == true)
{
isOn = false;
Console.Write("\nThe smartphone is shutting down...");
}
else
Console.Write("\nThe smartphone is already offline...");
}

// method definition for InstallApplication()


public void InstallApplication(string appName, double memoryRequirements)
{
if (isOn == true)
{
if (memoryRequirements <= RemainingMemory)
{
RemainingMemory = RemainingMemory - memoryRequirements;
Console.Write(appName + " was installed successfully.");
Console.Write("\nRemaining memory: " + RemainingMemory + " MB");
}
else
Console.Write("\nThe memory is not sufficient to install the application.");
}
else
{
Console.Write("\nCannot install while the smartphone is offline.");
}
}
}
}

Program.cs

5 | Page
namespace OOPExample
{
class Program
{
static void Main(string[] args)
{
int choice;
string appName;
double memoryRequirements;

// assigns values to the properties


Smartphone phone = new Smartphone();
Console.Write("\nEnter model: ");
phone.Model = Console.ReadLine();
Console.Write("\nEnter memory capacity in MB: ");
phone.InternalMemory = Convert.ToDouble(Console.ReadLine());
phone.RemainingMemory = phone.InternalMemory;

// calls the methods using a menu


do
{
Console.Write("\nMenu");
Console.Write("\n[1] Turn On");
Console.Write("\n[2] Turn Off");
Console.Write("\n[3] Install");
Console.Write("\n[4] Exit");
Console.Write("\nEnter choice: ");
choice = Convert.ToInt32(Console.ReadLine());

switch(choice)
{
case 1:
phone.TurnOn();
break;
case 2:
phone.TurnOff();
break;
case 3:
Console.Write("\nEnter application name to be installed: ");
appName = Console.ReadLine();
Console.Write("\nEnter size of application in MB: ");
memoryRequirements = Convert.ToDouble(Console.ReadLine());
phone.InstallApplication(appName, memoryRequirements);
break;
case 4:
Console.Write("\nEnd of program...");
Console.ReadKey();
break;
default:
Console.Write("\nInvalid choice!");
break;
}
} while (choice!=4);
}
}
}

6 | Page

You might also like