c4 Tuan 7 3 Tiet Oop

Embed Size (px)

Citation preview

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    1/50

    Object-Oriented ProgrammingChapter 4

    Ebook: Beginning Visual C# 2010, part 1, chapter 8,9,10,13

    Reference: DEITEL - CSharp How to Program

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    2/50

    Contents

    Review concepts in OOP Write classes in C#

    Interface

    Inheritance Polymorphism

    Relationships between objects

    Slide 2

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    3/50

    Review concepts in OOP

    Review concepts in OOP class

    object

    field

    property

    method

    event

    Other problems Static members: field, property and method (p.191)

    Static constructor (p.191)

    Static class (p.192)

    Slide 3

    ClassName

    - Fields

    + Methods

    Class diagram

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    4/50

    Contents

    Review concepts in OOP Write classes in C#

    Interface

    Inheritance Polymorphism

    Relationships between objects

    Slide 4

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    5/50

    Create a class in C#

    Slide 7

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    6/50

    Member access modifiers

    Without a access modifier: can be accessed by anyclass 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

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    7/50

    Writingproperties

    Properties(accessors): Contain two blocks: getand setthe value of the fields

    One of these blocks can be omitted to create read-onlyor write-only properties

    You can use Encapsulate Fieldfunction to properties

    Slide 9

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    8/50

    Writing constructors

    A constructor is a special method in a class that isinvoked when the object gets instantiated

    A constructor is used to initialize the properties of theobject

    Note to write a constructor:

    The name of the constructor and the name of the classare the same

    A constructor does not return value, not even void

    A class can have multiple constructors (overloadedconstructors) public ClassName (parameterList)

    {

    } Slide 10

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    9/50

    Instantiating an object

    To instantiate an object, using the new keyword

    Example:

    Lop l = new Lop();

    Lop c;

    c = new Lop(NCTH2K, Cao dang nghe 2K);

    ClassNameobject= newClassName ();

    ClassNameobject;object=newClassName ();

    Slide 11

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    10/50

    Using properties, methods of a class

    Call methods or properties of a class Using dotoperator

    Accessors:

    get: variable = object.propertyName

    set: object.propertyName = variable

    Example:

    Lop c = new Lop();

    c.MaLop = "NCTH2K"; // call set{}

    c.TenLop = "Cao dang nghe 2K"; // call set{}

    Slide 12

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    11/50

    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 generateUML-like diagrams of your code and use them to modifyprojects

    Slide 13

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    12/50

    staticclass members (p.191)

    Every object of a class has its own copy of all instancevariables

    How can all objects of a class share the same copy ofa variable?

    Declare variables using keyword static

    Static members can be fields, properties, methods

    When using static members, dont need to instantiatean object

    Slide 14

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    13/50

    staticclass 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{

    get { return count; }}

    }

    Slide 15

    Employee e1=newEmployee("A","AA");Employee e2=newEmployee("B","BB");e2 = new Employee("C", "CC");

    MessageBox.Show("S employee: "

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    14/50

    staticconstructors (p.191)

    Static constructorsmust have no access modifiers andcannot have any parameters

    In static constructors, cannot access nonstatic membervariables

    Static constructorsonly be called once Static constructorswill run before any instance of your

    class is created or static members are accessed

    Example:

    publicclass ABC{

    private static string name;

    static ABC() {

    name = static member;

    }} Slide 16

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    15/50

    constand readonlymembers

    To declare constant members (members whose valuewill never change) using:

    the keyword const

    const members are implicitly static

    const members must be initialized when they are declared

    the keyword readonly

    readonly members will be initialized in the constructor butnot change after that

    Slide 17

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    16/50

    constand readonlymembers (cont.)

    public class Constants{

    // PI l mt hng s const

    public constdouble PI = 3.14159;

    // radius l mt hng s cha c khi to

    public readonly int radius;

    public Constants( int radiusValue )

    {

    radius = radiusValue;

    }

    }

    Slide 18

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    17/50

    constand readonlymembers (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

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    18/50

    Contents

    Review concepts in OOP Write classes in C#

    Interface

    Inheritance Polymorphism

    Relationships between objects

    Slide 22

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    19/50

    Inheritance (p.194)

    Inheritance enables to create a new class that extendsan existing class

    The existing class is called the parent class, or superclass, or base class

    The new class is called the child classor subclass,derived class

    The child class inherits the properties and methodsof

    the parent class

    A programmer can tailor a child class as needed byadding new variablesor methods, or by modifying theinherited ones

    C# provides a common base class for all objects

    called Object class Slide 23

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    20/50

    Inheritance (cont.)

    Declare inheritance class

    Classes in C# may derive only from a single baseclass directly

    The protected modifier allows a child class to

    reference a variable or method directly in the parentclass

    A protected variable is visible to any class in the

    same namespace

    Slide 24

    ParentClass

    ChildClass

    public class ChildClass : ParentClass{

    // ...}

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    21/50

    The base reference

    Constructors are not inherited To invoke the parent's constructor

    The base reference can also be used to reference

    other variablesand methodsdefined in the parentsclass

    Slide 25

    : base (parameters);

    base.VariableName

    base.MethodName( parameters );

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    22/50

    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, Exceptioninner )

    : base( message, inner )

    {

    }

    } Slide 26

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    23/50

    Overriding methods

    A child class can redefine a base-class method; thismethod is called overridingmethod

    To be overridden, a base-class method must bedeclared virtual

    To write an overriding method, using overridekeyword in the method header

    To view the method header for a method, using ObjectBrowser

    Example: view Objects methods

    Slide 27

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    24/50

    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

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    25/50

    Example: class Point

    public class Point{private int x, y;

    public Point(){

    }public Point( int xValue, int yValue ){

    X = xValue; // use property XY = yValue; // use property Y

    }

    public int X{

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

    }

    Slide 29

    public int Y{

    get { return y; }

    set { y = value; }

    }

    public override string ToString()

    {

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

    }

    }

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    26/50

    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

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    27/50

    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 representationreturn "Center = " + base.ToString() + "; Radius = " + radius;

    }}

    Slide 31

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    28/50

    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 radiusstring 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 valuescircle.X = 2;

    circle.Y = 2;circle.Radius = 4.25;

    // display Circle3's string representationoutput += "\n\n" + "The new location and radius of circle are " + "\n" + circle +

    "\n";

    Slide 32

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    29/50

    Example: class CircleTest (cont.)

    // display Circle3's Diameteroutput += "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

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    30/50

    Contents

    Review concepts in OOP Write classes in C#

    Interface

    Inheritance Polymorphism

    Relationships between objects

    Slide 34

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    31/50

    Polymorphism (p.196)

    Polymorphism allows objects to be represented inmultiple forms

    Polymorphism via inheritance:All objects instantiatedfrom a derived class can be treated as if they were

    instances of a parent class

    Polymorphism via interface: p.197

    Slide 35

    Cow myCow = new Cow();

    Animal myAnimal = myCow;

    myAnimal.EatFood();

    // but not myAnimal.Moo();

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    32/50

    Abstractclasses and methods

    To define an abstractclass, a method or propertyabstract, use keyword abstract

    Abstractclasses can contain abstract methods orabstract properties

    Have no implementation

    Abstractclasses cannot be instantiated

    Abstractclasses are used as base classes from whichother classes may inherit

    Concrete classes use the keyword override to provideimplementations for all the abstract methods andproperties of the base-class

    Slide 36

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    33/50

    Polymorphism example

    Base-class Employee abstract

    abstract method Earnings

    Classes that derive from Employee

    Boss CommissionWorker

    PieceWorker

    HourlyWorker

    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

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    34/50

    Employee.cs

    publicabstractclass Employee{privatestring firstName;privatestring lastName;

    public Employee( string fnValue, string lnValue )

    {FirstName = fnValue;LastName = lnValue;

    }

    publicstring FirstName

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

    }

    Slide 38

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    35/50

    Employee.cs (cont.)

    publicstring LastName{

    get { return lastName; }

    set { lastName = value; }

    }

    publicoverridestring ToString()

    {

    return FirstName + " " + LastName;

    }

    // abstract method that must be implemented for each derived

    // class of Employee to calculate specific earnings

    publicabstractdecimal Earnings();

    }

    Slide 39

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    36/50

    Boss.cs

    publicclass Boss : Employee{

    privatedecimal salary;// Boss's salary

    // constructor

    public Boss( string firstNameValue, string lastNameValue, decimal salaryValue)

    : base( firstNameValue, lastNameValue )

    {

    WeeklySalary = salaryValue;

    }

    // property WeeklySalary

    publicdecimal WeeklySalary

    {

    get { return salary; }

    set { if ( value > 0 ) salary = value; }

    }

    Slide 40

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    37/50

    Boss.cs (cont.)

    // override base-class method to calculate Boss's earningspublicoverridedecimal Earnings()

    {

    return WeeklySalary;

    }

    // return string representation of Boss

    publicoverridestring ToString()

    {

    return"Boss: " + base.ToString();

    }

    }

    Slide 41

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    38/50

    CommisionWorker.cs

    publicclass CommissionWorker : Employee{

    privatedecimal salary; // base weekly salary

    privatedecimal commission; // amount paid per item sold

    privateint quantity; // total items sold

    // constructor

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

    : base( firstNameValue, lastNameValue )

    {WeeklySalary = salaryValue;

    Commission = commissionValue;

    Quantity = quantityValue;

    }

    Slide 42

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    39/50

    CommisionWorker.cs (cont.)

    // property WeeklySalary

    publicdecimal WeeklySalary

    {

    get { return salary; }

    set { if ( value > 0 ) salary = value; }

    }

    // property Commissionpublicdecimal Commission

    {

    get { return commission; }

    set { if ( value > 0 ) commission = value; }

    }

    // property Quantity

    publicint Quantity

    {

    get { return quantity; }

    Slide 43

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    40/50

    CommisionWorker.cs (cont.)

    set { if ( value > 0 ) quantity = value; }}

    // override base-class method to calculate CommissionWorker's earnings

    publicoverridedecimal Earnings()

    {return WeeklySalary + Commission * Quantity;

    }

    // return string representation of CommissionWorker

    publicoverridestring ToString(){

    return"CommissionWorker: " + base.ToString();

    }

    }

    Slide 44

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    41/50

    PieceWorker.cs

    publicclass PieceWorker : Employee{privatedecimal wagePerPiece;// wage per piece producedprivateint quantity; // quantity of pieces producedpublic PieceWorker( string firstNameValue, string lastNameValue,

    decimal wagePerPieceValue, int quantityValue )

    : base( firstNameValue, lastNameValue ){WagePerPiece = wagePerPieceValue;Quantity = quantityValue;

    }

    // property WagePerPiecepublicdecimal WagePerPiece{

    get { return wagePerPiece; }set { if ( value > 0 ) wagePerPiece = value; }

    }

    Slide 45

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    42/50

    PieceWorker.cs (cont.)

    // property Quantitypublicint Quantity

    {

    get { return quantity; }

    set { if ( value > 0 ) quantity = value; }

    }

    // override base-class method to calculate PieceWorker's earnings

    publicoverridedecimal Earnings()

    {

    return Quantity * WagePerPiece;

    }

    // return string representation of PieceWorkerpublicoverridestring ToString()

    {

    return"PieceWorker: " + base.ToString();

    }

    }Slide 46

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    43/50

    HourlyWorker.cs

    publicclass HourlyWorker : Employee{

    privatedecimal wage; // wage per hour of workprivatedouble hoursWorked;// hours worked during week

    // constructorpublic HourlyWorker( string firstNameValue, string LastNameValue,

    decimal wageValue, double hoursWorkedValue ): base( firstNameValue, LastNameValue )

    {Wage = wageValue;HoursWorked = hoursWorkedValue;

    }

    // property Wagepublicdecimal Wage{

    get { return wage; }set { if ( value > 0 ) wage = value; }

    } Slide 47

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    44/50

    HourlyWorker.cs (cont.)

    // property HoursWorkedpublicdouble HoursWorked

    {

    get { return hoursWorked; }

    set { if ( value > 0 ) hoursWorked = value; }

    }

    // override base-class method to calculate HourlyWorker earnings

    publicoverridedecimal Earnings()

    {

    // compensate for overtime (paid "time-and-a-half")if ( HoursWorked

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    45/50

    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

    publicoverridestring ToString()

    {return"HourlyWorker: " + base.ToString();

    }

    }

    Slide 49

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    46/50

    EmployeesTest.cs

    publicclass EmployeesTest {

    publicstaticvoid 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

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    47/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 informationpublicstaticstring GetString( Employee worker )

    {return worker.ToString() + " earned " +worker.Earnings().ToString( "C" ) + "\n";

    }}

    Slide 51

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    48/50

    Contents

    Review concepts in OOP Write classes in C#

    Interface

    Inheritance Polymorphism

    Relationships between objects

    Slide 52

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    49/50

    Relationships between objects

    Containment: One class contains another

    Slide 53

  • 7/31/2019 c4 Tuan 7 3 Tiet Oop

    50/50

    Relationships between objects (cont.)

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