56
OBJECT-ORIENTED PROGRAMMING Classes, Objects, Inheritance, Advantages, OOP Concepts, Application, Object-Oriented Programming in C#

Introduction to Object-Oriented Programming

  • Upload
    pangjei

  • View
    363

  • Download
    2

Embed Size (px)

DESCRIPTION

Object-Oriented Programming

Citation preview

Page 1: Introduction to Object-Oriented Programming

OBJECT-ORIENTED PROGRAMMINGClasses, Objects, Inheritance, Advantages, OOP Concepts, Application, Object-Oriented Programming in C#

Page 2: Introduction to Object-Oriented Programming

Overview

Object-oriented programming (OOP) Encapsulates data (attributes) and

functions (behavior) into packages called classes.

So, Classes are user-defined (programmer-defined) types. Data (data members) Functions (member functions or methods)

In other words, they are structures + functions

Page 3: Introduction to Object-Oriented Programming

Understanding Object-Oriented Programming (1/2)

C# is object-oriented. What does that mean? Unlike languages, such as FORTRAN, which focus on giving the computer imperative "Do this/Do that" commands, object-oriented languages focus on data.

Object-oriented programs still tell the computer what to do. They start, however, by organizing the data, and the commands come later.

Page 4: Introduction to Object-Oriented Programming

Understanding Object-Oriented Programming (2/2)

Object-oriented languages are better than "Do this/Do that" languages because they organize data in a way that lets people do all kinds of things with it.

To modify the data, you can build on what you already have, rather than scrap everything you've done and start over each time you need to do something new.

Page 5: Introduction to Object-Oriented Programming

Need for OOP Paradigm

OOP was developed to overcome the limitations of the traditional programming languages

As the programs gets larger in procedural programming it becomes more complex to understand the logic and implement

Page 6: Introduction to Object-Oriented Programming

Advantages of OOP

It allows reusability of code OOP can be upgrade from small to large

scale Easy to partition the work Reduces the software maintenance &

development costs Change in user requirement or later

development always been a major problem. OOP resolves this kind of problem.

Page 7: Introduction to Object-Oriented Programming

What is a class?

A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions as members.

It is an encapsulation of attributes and methods.

A class is essentially like a blueprint, from which you can create objects.

From one class, any number of instances can be created.

Page 8: Introduction to Object-Oriented Programming

PEN

Page 9: Introduction to Object-Oriented Programming

What is an object?

An object is an instance of a class. In terms of variables, a class would be the type,

and an object would be the variable. If a class is like a blueprint, then an object is

what is created from that blueprint. The class is the definition of an item; the object

is the item. The blueprint for your house is like a class; the

house that you live in is an object.

Page 10: Introduction to Object-Oriented Programming

Objects created from the class Student

Student ClassNameAge

Object Student: JohnName: John SmithAge:23

Object Student: BlairName: Blair SmithAge:16

Object Student: ….Name: …Age:…

Objects of the class Student

Page 11: Introduction to Object-Oriented Programming

Class vs. Object

Vehicle Car

Animal Elephant

Person Student

Flower Rose

Page 12: Introduction to Object-Oriented Programming

Declaring a Class in C# (1/2) Syntax:

[accessSpecifier] class ClassName {

[accessSpecifier] member1;[accessSpecifier] member2;...

}

Page 13: Introduction to Object-Oriented Programming

Declaring a Class in C# (2/2) A class definition begins with the

keyword class. The body of the class is contained within

a set of braces, { }. A class definition is stored in a file with a

.cs filename extension.class ClassName{

…………

}Class body (data member + methods)

Any valid identifier

Page 14: Introduction to Object-Oriented Programming

Member Access Specifiers (1/2) public

can be accessed outside the class directly. The public stuff is the interface.

private Accessible only to member functions of

class. Private members and methods are for

internal use only. protected

Members are accessible from members of their same class and from their friends, but also from members of their derived classes.

Page 15: Introduction to Object-Oriented Programming

Member Access Specifiers (2/2) By default, all members of a class

declared with the class keyword have private access for all its members.

Usually, the data members of a class are declared private and the member functions are public.

Page 16: Introduction to Object-Oriented Programming

Why do we need private variables? Encapsulation - not forcing unnecessary

information on the user of the class. Managing complexity – a public variable

could be anywhere – if something goes wrong, error tracking is much difficult.

Page 17: Introduction to Object-Oriented Programming

Class Example

This class example shows how we can encapsulate (gather) a circle information into one package (unit or class)

No need for others classes to access and retrieve its value directly. Theclass methods are responsible forthat only.

class Circle{private double radius;public void setRadius(double r) public double getDiameter()public double getArea()public double getCircumference()}

They are accessible from outsidethe class, and they can access themember (radius)

Page 18: Introduction to Object-Oriented Programming

How to Write a Method

A method is a class member that is used to define the actions that can be performed by that object or class.

Syntax:[AccessSpecifier] [ReturnType]

MethodName([parameterlist])

{

statements

}

Page 19: Introduction to Object-Oriented Programming

Rules

In the method declaration, you must always specify a return type.

If the method is not designed to return a value to the caller, you specify a return type of void.

Even if the method takes no arguments, you must include a set of empty parentheses after the method name.

When calling a method, you must match the input parameters of the method exactly, including the return type, the number of parameters, their order, and their type.

The method name and parameter list is known as the method signature.

Page 20: Introduction to Object-Oriented Programming

Recommendation

The following are recommendations for naming methods: The name of a method should represent

the action that you want to carry out. For this reason, methods usually have action-oriented names, such as WriteLine and ChangeAddress.

Methods should be named using Pascal case.

Page 21: Introduction to Object-Oriented Programming

How to Pass Parameter to a MethodPass by ValueWhen you pass a variable as a parameter, the

method works on a copy of that variable. This is called passing by value, because the value is provided to the method, yet the object that contains the value is not changed.

//if the method returns a value

var = methodName (argument1, argument 2, …); 11

//the method does not return a value methodName (argument1, argument 2, …);

Page 22: Introduction to Object-Oriented Programming

Example 1: Pass by Value

class SimpleMath {

public int Add( int x, int y ) {

return x + y;}

}…SimpleMath sums = new SimpleMath();int total = sums.Add ( 20, 30 ); //total = ?

Page 23: Introduction to Object-Oriented Programming

Example 2: Pass by Value

class SimpleMath{

public void Double( int doubleTarget ){

doubleTarget = doubleTarget * 2;}

}……SimpleMath sums = new SimpleMath();int numbertoDouble = 10;sums.Double ( numbertoDouble);MessageBox.Show(numbertoDouble); //what is the

output?

Page 24: Introduction to Object-Oriented Programming

How to Pass Parameter to a MethodPass by ReferenceWhen you pass a variable as a reference, the

method works on a the reference of that variable. This is called passing by reference, because the reference to the object is provided to the method, yet the object that contains the value is changed.

//if the method returns a value

var = methodName (ref arg1, ref arg2, …); //the method does not return a value methodName (ref arg1, ref arg 2, …);

Page 25: Introduction to Object-Oriented Programming

Example 1: Pass by Referenceclass SimpleMath{

public void Double( ref int doubleTarget ) {

doubleTarget = doubleTarget * 2;}

}……SimpleMath sums = new SimpleMath();int numbertoDouble = 10;sums.Double ( ref numbertoDouble);MessageBox.Show(numbertoDouble); //what is

the output?

Page 26: Introduction to Object-Oriented Programming

Example 2: Pass by Referenceclass Sample{

public void Test(ref int x, ref int y){ x = x * 3; y = y + 5; }

}…a = 5; b = 4;MessageBox.Show( a + “\t” + b); //what is the

output?Sample s = new Sample();s.Test (ref a, ref b);MessageBox.Show( a + “\t” + b); //what is the

output?

Page 27: Introduction to Object-Oriented Programming

Creating an object of a Class Declaring a variable of a class type

creates an object. You can have many variables of the same type (class) Instantiation

Syntax:ClassName objectName = new

ClassName(); You can instantiate many objects from a

class type. Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle();

Page 28: Introduction to Object-Oriented Programming

Example

class Rectangle { float w, h;public void SetValues (float width, float height){

w = width; h = height;}

public float Area(){

return w * h;}

}

Page 29: Introduction to Object-Oriented Programming

Accessing members of a class Rectangle rect = new Rectangle(); We can refer within the body of the

program to any of the public members of

the object rect as if they were normal

functions or normal variables, just by

putting the object's name followed by a dot

(.) and then the name of the member. rect.SetValues (3,4); float myarea = rect.Area();

Page 30: Introduction to Object-Oriented Programming
Page 31: Introduction to Object-Oriented Programming

this keyword

The this keyword is used to refer to the current instance of an object. When this is used within a method, it allows you to refer to the members of the object.

Page 32: Introduction to Object-Oriented Programming

Example

class Lion {

private int weight;public bool IsNormalWeight() {

if ( ( this.weight < 100 ) || (this.weight > 250 ) ) {

return false;}return true;

}public void Eat() { }public int GetWeight() {

return this.weight;}

}

Page 33: Introduction to Object-Oriented Programming

Review Questions

1. A house is to a blueprint as a(n) _______ is to a class.

2. Every class definition contains keyword _________ followed immediately by the class's name.

3. A class definition is typically stored in a file with the _________ filename extension.

4. Each parameter in a function header should specify both a(n) _________ and a(n) _________.

5. When each object of a class maintains its own copy of an attribute, the variable that represents the attribute is also known as a(n) _________.

Page 34: Introduction to Object-Oriented Programming

Review Questions

6. Keyword public is a(n) _________.

7. Return type _________ indicates that a function will perform a task but will not return any information when it completes its task.

Page 35: Introduction to Object-Oriented Programming

Answers to Review Questions1. object

2. class

3. .cs

4. type, name

5. data member

6. access specifier

7. void

Page 36: Introduction to Object-Oriented Programming

Properties (1/2)

Properties are methods that protect access to class members

Syntax:[AccessSpecifier][ReturnType] PropertyName

{

get { }

set { }

}

In C# 3.0, properties can be written as:public string Name { get; set; }

Page 37: Introduction to Object-Oriented Programming

Properties (2/2)

get and set are called accessors The get accessor must return a type that is

the same as the property type, or one that can be implicitly converted to the property type.

The set accessor is equivalent to a method that has one implicit parameter, named value.

Equivalent to getter and setter methods

Page 38: Introduction to Object-Oriented Programming

Example 1

Page 39: Introduction to Object-Oriented Programming

Example 2

Page 40: Introduction to Object-Oriented Programming

Constructor (1/2)

Is a special member function public function member Automatically called when a new object

is created (instantiated). Initialize data members. Constructors cannot be called explicitly

as if they were regular member functions. They are only executed when a new object of that class is created.

Several constructorsFunction overloading

Page 41: Introduction to Object-Oriented Programming

Constructor (2/2)

Objects generally need to initialize variables or assign dynamic memory during their process of creation to become operative and to avoid returning unexpected values during their execution.

In order to avoid that, a class can include a special function called constructor to initialize data members of the class

This constructor function must have the same name as the class, and cannot have any return type; not even void.

Page 42: Introduction to Object-Oriented Programming

Constructor

class Circle{ private double radius; public Circle() public Circle(int r) public void setRadius(double r) public double getDiameter() public double getArea() public double getCircumference()}

Constructor with no argument

Constructor with one argument

Page 43: Introduction to Object-Oriented Programming
Page 44: Introduction to Object-Oriented Programming

Overloading Constructors

Like any other function, a constructor can also be overloaded with more than one function that have the same name but different types or number of parameters.

Do use constructor parameters as shortcuts for setting main properties.

Page 45: Introduction to Object-Oriented Programming

Overloading Constructors

class Square{ double side;

public Square(){

side = 0;}

public Square(double s){

side = s*s;}

}

Page 46: Introduction to Object-Oriented Programming

Parameterized Constructor

If you do not declare any constructors in a class definition, the compiler assumes the class to have a default constructor with no arguments.

As soon as you declare your own constructor for a class, the compiler no longer provides an implicit default constructor. So you have to declare all objects of that class according to the parameters of the constructor you defined for the class.

Page 47: Introduction to Object-Oriented Programming

Example

public class Lion

{

private string name;

public Lion( string newLionName )

{

this.name = newLionName;

}

}

Lion babyLion = new Lion ("Leo"); //name = ?

Lion babyLion = new Lion (""); //name = ?

Lion babyLion = new Lion (); //name = ?

Page 48: Introduction to Object-Oriented Programming

Non-Example

Page 49: Introduction to Object-Oriented Programming

Readonly

When you use the readonly modifier on a member variable, you can only assign it a value when the class or object initializes, either by directly assigning the member variable a value, or by assigning it in the constructor.

Use the readonly modifier when a const keyword is not appropriate because you are not using a literal value—meaning that the actual value of the variableis not known at the time of compilation.

Page 50: Introduction to Object-Oriented Programming

Example

class Zoo {

private int numberAnimals;public readonly decimal admissionPrice;public Zoo() {

if ( numberAnimals > 50 ) admissionPrice = 25;

else admissionPrice = 20;

}}Zoo z = new Zoo();

Page 51: Introduction to Object-Oriented Programming

How to Use Static Class Members

Static Members Belong to the class Initialize before an instance of the

class is created Shared by all instances of the class

class Lion{public static string family =

“felidae”;}…//a lion object is not created in this coderchDisplay.Text = “Family:” + Lion.family;

Page 52: Introduction to Object-Oriented Programming

using System; namespace MyCompany { public class Employee { public decimal Salary; public const int MaxOTHours = 10; public static double EmpNo;

public Employee() { EmpNo++; } }

Example: Static Member

public class EmployeeTest { static void Main(string[] args) { Employee Michael = new Employee(); Employee Youssef = new Employee(); Employee David = new Employee(); Console.WriteLine (Employee.EmpNo); Console.ReadLine(); } }

Page 53: Introduction to Object-Oriented Programming

Activity

Create a class called Employee that includes three pieces of information as data members: a first name (type string), a last name (type string) and a monthly salary (type double).

Your class should have a constructor that initializes the three data members.

Provide a set and a get function for each data member. If the monthly salary is not positive, set it to 0.

Write a test program that demonstrates class Employee's capabilities. Create two Employee objects and display each object's yearly salary. Then give each Employee a 10 percent raise and display each Employee's yearly salary again.

Page 54: Introduction to Object-Oriented Programming

Answer: Employee Class

Page 55: Introduction to Object-Oriented Programming

Answer: Test Program