Sie sind auf Seite 1von 56

OBJECT-ORIENTED PROGRAMMING

Classes, Objects, Inheritance, Advantages, OOP Concepts, Application, Object-Oriented Programming in C#

Overview

Object-oriented programming (OOP)


Encapsulates

data (attributes) and functions (behavior) into packages called classes.

So, Classes are user-defined (programmerdefined) types.


Data

(data members) Functions (member functions or methods)

In other words, they are structures + functions

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.

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.

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

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.

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.

PEN

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.

Objects created from the class Student


Objects of the class Student

Student Class Name Age Object Student: John Name: John Smith Age:23

Object Student: Blair Name: Blair Smith Age:16

Object Student: . Name: Age:

Class vs. Object


Vehicle Animal Person Flower Car Elephant Student Rose

Declaring a Class in C# (1/2)

Syntax:

[accessSpecifier] class ClassName { [accessSpecifier] member1; [accessSpecifier] member2; ...

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 { }
Any valid identifier

Class body (data member + methods)

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.

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.

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.

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. The class methods are responsible for that only.

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

They are accessible from outside the class, and they can access the member (radius)

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 }

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.

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.

How to Pass Parameter to a Method


Pass by Value When 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, );

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 = ?

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?

How to Pass Parameter to a Method


Pass by Reference When 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, );

Example 1: Pass by Reference


class 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?

Example 2: Pass by Reference


class 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?

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();

Example
class Rectangle { float w, h; public void SetValues (float width, float height) { w = width; h = height; } public float Area() { return w * h; } }

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();

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.

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; } }

Review Questions
1.

2.

3.

4.

5.

A house is to a blueprint as a(n) _______ is to a class. Every class definition contains keyword _________ followed immediately by the class's name. A class definition is typically stored in a file with the _________ filename extension. Each parameter in a function header should specify both a(n) _________ and a(n) _________. 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) _________.

Review Questions
6.

7.

Keyword public is a(n) _________. Return type _________ indicates that a function will perform a task but will not return any information when it completes its task.

Answers to Review Questions


1.

2.
3. 4. 5. 6. 7.

object class .cs type, name data member access specifier void

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; }

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

Example 1

Example 2

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 constructors Function overloading

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.

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

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.

Overloading Constructors
class Square { double side; public Square() { side = 0; } public Square(double s) { side = s*s; } }

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.

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 = ?

Non-Example

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 valuemeaning that the actual value of the variable is not known at the time of compilation.

Example
class Zoo { private int numberAnimals; public readonly decimal admissionPrice; public Zoo() { if ( numberAnimals > 50 ) admissionPrice = 25; else admissionPrice = 20; } } Zoo z = new Zoo();

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 code rchDisplay.Text = Family: + Lion.family;

Example: Static Member


using System; namespace MyCompany { public class Employee { public decimal Salary; public const int MaxOTHours = 10; public static double EmpNo; public Employee() { EmpNo++; } } 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(); } }

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.

Answer: Employee Class

Answer: Test Program

References

Introduction to C# Programming with Microsoft.NET http://programmers.stackexchange.com http://www.dummies.com/howto/content/understanding-javas-objectorientedprogramming-oop.html#ixzz1AYfDuLbW

Das könnte Ihnen auch gefallen