Você está na página 1de 50

Object-Oriented Programming

Chapter 4
Ebook: Beginning Visual C# 2010, part 1, chapter 8,9,10,13 Reference: DEITEL - CSharp How to Program

Contents

Review concepts in OOP Write classes in C# Interface Inheritance Polymorphism Relationships between objects

Slide 2

Review concepts in OOP

Review concepts in OOP


class object field property method event

ClassName - Fields + Methods


Class diagram

Other problems

Static members: field, property and method (p.191) Static constructor (p.191) Static class (p.192)
Slide 3

Contents

Review concepts in OOP Write classes in C# Interface Inheritance Polymorphism Relationships between objects

Slide 4

Create a class in C#

Slide 7

Member access modifiers

Without a access modifier: can be accessed by any class in the same namespace private: can only be accessed from inside the class public: can be accessed from anywhere protected: can be accessed from inside the child class or any class in the same namespace

Slide 8

Writing properties

Properties (accessors):

Contain two blocks: get and set the value of the fields One of these blocks can be omitted to create read-only or write-only properties You can use Encapsulate Field function to properties

Slide 9

Writing constructors

A constructor is a special method in a class that is invoked when the object gets instantiated A constructor is used to initialize the properties of the object Note to write a constructor:

The name of the constructor and the name of the class are the same A constructor does not return value, not even void

A class can have multiple constructors (overloaded constructors) public ClassName (parameterList)
{ }
Slide 10

Instantiating an object

To instantiate an object, using the new keyword

ClassName object = new ClassName ();


ClassName object; object = new ClassName ();

Example:
Lop l = new Lop(); Lop c; c = new Lop(NCTH2K, Cao dang nghe 2K);
Slide 11

Using properties, methods of a class

Call methods or properties of a class

Using dot operator

Accessors:

get: set:

variable = object.propertyName object.propertyName = variable

Example:
Lop c = new Lop(); c.MaLop = "NCTH2K"; c.TenLop = "Cao dang nghe 2K";

// call set{} // call set{}

Slide 12

OOP tools in VS

The Class View Window (p.222)

Menu View\Class View

The Object Browser (p.224)

Menu View\Object Browser

Class Diagrams (p.227)

The class diagram editor in VS enables you to generate UML-like diagrams of your code and use them to modify projects

Slide 13

static class members (p.191)

Every object of a class has its own copy of all instance variables How can all objects of a class share the same copy of a variable?

Declare variables using keyword static

Static members can be elds, properties, methods When using static members, dont need to instantiate an object

Slide 14

static class members (cont.)


public class Employee { private string firstName; private string lastName; private static int count; // Employee objects in memory public Employee( string fName, string lName ) { firstName = fName; lastName = lName; count++; } public static int Count Employee e1=new { Employee("A","AA"); get { return count; } Employee e2=new } Employee("B","BB"); } e2 = new Employee("C", "CC"); MessageBox.Show("S employee: " 15 Slide

static constructors (p.191)

Static constructors must have no access modiers and cannot have any parameters

In static constructors, cannot access nonstatic member variables

Static constructors only be called once Static constructors will run before any instance of your class is created or static members are accessed Example:
public class ABC{ private static string name; static ABC() { name = static member; } }

Slide 16

const and readonly members

To declare constant members (members whose value will never change) using:

the keyword const


const members are implicitly static const members must be initialized when they are declared readonly members will be initialized in the constructor but not change after that

the keyword readonly

Slide 17

const and readonly members (cont.)


public class Constants { // PI l mt hng s const public const double PI = 3.14159; // radius l mt hng s cha c khi to public readonly int radius; public Constants( int radiusValue ) { radius = radiusValue; } }
Slide 18

const and readonly members (cont.)


public class UsingConstAndReadOnly { static void Main( string[] args ) { Random random = new Random(); Constants constantValues = new Constants( random.Next( 1, 20 ) ); MessageBox.Show( "Radius = " + constantValues.radius + "\nCircumference = " + 2 * Constants.PI * constantValues.radius, "Circumference" ); } }

Slide 19

Contents

Review concepts in OOP Write classes in C# Interface Inheritance Polymorphism Relationships between objects

Slide 22

Inheritance (p.194)

Inheritance enables to create a new class that extends an existing class


The existing class is called the parent class, or super class, or base class The new class is called the child class or subclass, derived class

The child class inherits the properties and methods of the parent class

A programmer can tailor a child class as needed by adding new variables or methods, or by modifying the inherited ones
Slide 23

C# provides a common base class for all objects called Object class

Inheritance (cont.)

Declare inheritance class


public class ChildClass : ParentClass { // ... }

ParentClass

ChildClass

Classes in C# may derive only from a single base class directly The protected modifier allows a child class to reference a variable or method directly in the parent class

A protected variable is visible to any class in the same namespace


Slide 24

The base reference


Constructors are not inherited : To invoke the parent's constructorbase (parameters); The base reference can also be used to reference other variables and methods defined in the parents class
base.VariableName base.MethodName( parameters );

Slide 25

The base reference (cont.)


public class NegativeNumberException : ApplicationException { public NegativeNumberException() : base( "Phai nhap vao so khong am" ) { } public NegativeNumberException( string message ) : base( message ) { } public NegativeNumberException( string message, Exception inner ) : base( message, inner ) { } } Slide 26

Overriding methods

A child class can redefine a base-class method; this method is called overriding method To be overridden, a base-class method must be declared virtual To write an overriding method, using override keyword in the method header To view the method header for a method, using Object Browser

Example: view Objects methods

Slide 27

Object class (p.215)

All classes inherit from Object


All classes have access to the protected and public members of this class (table p.215) You can override some methods of Object class (if a method is being overridden)

Example:

public override string ToString()

Some Objects methods:


ToString(): example ... Equals(object): example ... GetHashCode(): example ...

Slide 28

Example: class Point


public class Point { private int x, y; public Point() { } public Point( int xValue, int yValue ) { X = xValue; // use property X Y = yValue; // use property Y } public int X { get { return x; } set { x = value; } } public int Y {

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

public override string ToString()


{ return "[" + x + ", " + y + "]"; } }

Slide 29

Example: class Circle


public class Circle : Point { private double radius; public Circle() { } public Circle( int xValue, int yValue, double radiusValue ) : base( xValue, yValue ) { radius = radiusValue; } public double Radius { get { return radius; } set { if ( value >= 0 ) radius = value; } }

Slide 30

Example: class Circle (cont.)


public double Diameter() { return radius * 2; } public double Circumference() { return Math.PI * Diameter(); } public double Area() { return Math.PI * Math.Pow( radius, 2 ); } public override string ToString() { // use base reference to return Point string representation return "Center = " + base.ToString() + "; Radius = " + radius; } }
Slide 31

Example: class CircleTest


class CircleTest { static void Main( string[] args ) { Circle circle = new Circle( 37, 43, 2.5 ); // get Circle3's initial x-y coordinates and radius string output = "X coordinate is " + circle.X + "\n" + "Y coordinate is " + circle.Y + "\nRadius is " + circle.Radius; // set Circle3's x-y coordinates and radius to new values circle.X = 2; circle.Y = 2; circle.Radius = 4.25; // display Circle3's string representation output += "\n\n" + "The new location and radius of circle are " + "\n" + circle + "\n";
Slide 32

Example: class CircleTest (cont.)


// display Circle3's Diameter output += "Diameter is " + String.Format( "{0:F}", circle.Diameter() ) + "\n"; // display Circle3's Circumference output += "Circumference is " + String.Format( "{0:F}", circle.Circumference() ) + "\n"; // display Circle3's Area output += "Area is " + String.Format( "{0:F}", circle.Area() ); MessageBox.Show( output, "Demonstrating Class Circle3" ); } }

Slide 33

Contents

Review concepts in OOP Write classes in C# Interface Inheritance Polymorphism Relationships between objects

Slide 34

Polymorphism (p.196)

Polymorphism allows objects to be represented in multiple forms

Polymorphism via inheritance: All objects instantiated from a derived class can be treated as if they were instances of a parent class
Cow myCow = new Cow(); Animal myAnimal = myCow; myAnimal.EatFood(); // but not myAnimal.Moo();

Polymorphism via interface: p.197


Slide 35

Abstract classes and methods


To define an abstract class, a method or property abstract, use keyword abstract Abstract classes can contain abstract methods or abstract properties

Have no implementation

Abstract classes cannot be instantiated Abstract classes are used as base classes from which other classes may inherit Concrete classes use the keyword override to provide implementations for all the abstract methods and properties of the base-class
Slide 36

Polymorphism example

Base-class Employee

abstract abstract method Earnings Boss CommissionWorker PieceWorker HourlyWorker

Classes that derive from Employee


All derived-classes implement method Earnings Driver program uses Employee references to refer to instances of derived-classes Polymorphism calls the correct version of Earnings
Slide 37

Employee.cs
public abstract class Employee { private string firstName; private string lastName; public Employee( string fnValue, string lnValue ) { FirstName = fnValue; LastName = lnValue; } public string FirstName { get { return firstName; } set { firstName = value; } }

Slide 38

Employee.cs (cont.)
public string LastName { get { return lastName; } set { lastName = value; } } public override string ToString() { return FirstName + " " + LastName; }

// abstract method that must be implemented for each derived // class of Employee to calculate specific earnings public abstract decimal Earnings();
}
Slide 39

Boss.cs
public class Boss : Employee { private decimal salary; // Boss's salary // constructor public Boss( string firstNameValue, string lastNameValue, decimal salaryValue) : base( firstNameValue, lastNameValue ) { WeeklySalary = salaryValue; } // property WeeklySalary public decimal WeeklySalary { get { return salary; } set { if ( value > 0 ) salary = value; } }
Slide 40

Boss.cs (cont.)
// override base-class method to calculate Boss's earnings public override decimal Earnings() { return WeeklySalary; } // return string representation of Boss public override string ToString() { return "Boss: " + base.ToString(); } }
Slide 41

CommisionWorker.cs
public class CommissionWorker : Employee {

private decimal salary;


private int quantity; // constructor

// base weekly salary


// total items sold

private decimal commission; // amount paid per item sold

public CommissionWorker( string firstNameValue, string lastNameValue, decimal salaryValue, decimal commissionValue, int quantityValue )
: base( firstNameValue, lastNameValue ) {

WeeklySalary = salaryValue;
Commission = commissionValue; Quantity = quantityValue; }
Slide 42

CommisionWorker.cs (cont.)
// property WeeklySalary public decimal WeeklySalary { get { return salary; } set { if ( value > 0 ) salary = value; } } // property Commission public decimal Commission { get { return commission; } set { if ( value > 0 ) commission = value; } }

// property Quantity public int Quantity { get { return quantity; }


Slide 43

CommisionWorker.cs (cont.)
set { if ( value > 0 ) quantity = value; } } // override base-class method to calculate CommissionWorker's earnings public override decimal Earnings() { return WeeklySalary + Commission * Quantity; } // return string representation of CommissionWorker public override string ToString() { return "CommissionWorker: " + base.ToString(); } }
Slide 44

PieceWorker.cs
public class PieceWorker : Employee { private decimal wagePerPiece; // wage per piece produced private int quantity; // quantity of pieces produced public PieceWorker( string firstNameValue, string lastNameValue, decimal wagePerPieceValue, int quantityValue ) : base( firstNameValue, lastNameValue ) { WagePerPiece = wagePerPieceValue; Quantity = quantityValue; } // property WagePerPiece public decimal WagePerPiece { get { return wagePerPiece; } set { if ( value > 0 ) wagePerPiece = value; } }
Slide 45

PieceWorker.cs (cont.)
// property Quantity public int Quantity { get { return quantity; } set { if ( value > 0 ) quantity = value; } } // override base-class method to calculate PieceWorker's earnings public override decimal Earnings() { return Quantity * WagePerPiece; } // return string representation of PieceWorker public override string ToString() { return "PieceWorker: " + base.ToString(); } }
Slide 46

HourlyWorker.cs
public class HourlyWorker : Employee { private decimal wage; // wage per hour of work private double hoursWorked; // hours worked during week // constructor public HourlyWorker( string firstNameValue, string LastNameValue, decimal wageValue, double hoursWorkedValue ) : base( firstNameValue, LastNameValue ) { Wage = wageValue; HoursWorked = hoursWorkedValue; } // property Wage public decimal Wage { get { return wage; } set { if ( value > 0 ) wage = value; } }

Slide 47

HourlyWorker.cs (cont.)
// property HoursWorked public double HoursWorked { get { return hoursWorked; } set { if ( value > 0 ) hoursWorked = value; } } // override base-class method to calculate HourlyWorker earnings public override decimal Earnings() { // compensate for overtime (paid "time-and-a-half") if ( HoursWorked <= 40 ) { return Wage * Convert.ToDecimal( HoursWorked ); } else {
Slide 48

HourlyWorker.cs (cont.)
// calculate base and overtime pay decimal basePay = Wage * Convert.ToDecimal( 40 ); decimal overtimePay = Wage * 1.5M * Convert.ToDecimal( HoursWorked - 40 ); return basePay + overtimePay; } } // return string representation of HourlyWorker public override string ToString() { return "HourlyWorker: " + base.ToString(); } }

Slide 49

EmployeesTest.cs
public class EmployeesTest { public static void Main( string[] args ){ Boss boss = new Boss( "John", "Smith", 800 ); CommissionWorker commissionWorker = new CommissionWorker( "Sue", "Jones", 400, 3, 150 ); PieceWorker pieceWorker = new PieceWorker( "Bob", "Lewis", Convert.ToDecimal( 2.5 ), 200 );

HourlyWorker hourlyWorker = new HourlyWorker( "Karen", "Price", Convert.ToDecimal( 13.75 ), 50 );


Employee employee = boss; string output = GetString( employee ) + boss + " earned " + boss.Earnings().ToString( "C" ) + "\n\n"; employee = commissionWorker; output += GetString( employee ) + commissionWorker + " earned " + commissionWorker.Earnings().ToString( "C" ) + "\n\n"; employee = pieceWorker;

Slide 50

EmployeesTest.cs (cont.)
output += GetString( employee ) + pieceWorker + " earned " + pieceWorker.Earnings().ToString( "C" ) + "\n\n"; employee = hourlyWorker; output += GetString( employee ) + hourlyWorker + " earned " + hourlyWorker.Earnings().ToString( "C" ) + "\n\n"; MessageBox.Show( output, "Demonstrating Polymorphism, MessageBoxButtons.OK, MessageBoxIcon.Information ); } // return string that contains Employee information public static string GetString( Employee worker ) { return worker.ToString() + " earned " + worker.Earnings().ToString( "C" ) + "\n"; } }

Slide 51

Contents

Review concepts in OOP Write classes in C# Interface Inheritance Polymorphism Relationships between objects

Slide 52

Relationships between objects

Containment: One class contains another

Slide 53

Relationships between objects (cont.)

Collections: One class acts as a container for multiple instances (arrays of objects) of another class

Slide 54

Você também pode gostar