Escolar Documentos
Profissional Documentos
Cultura Documentos
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
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
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
Example:
Lop l = new Lop(); Lop c; c = new Lop(NCTH2K, Cao dang nghe 2K);
Slide 11
Accessors:
get: set:
Example:
Lop c = new Lop(); c.MaLop = "NCTH2K"; c.TenLop = "Cao dang nghe 2K";
Slide 12
OOP tools in VS
The class diagram editor in VS enables you to generate UML-like diagrams of your code and use them to modify projects
Slide 13
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?
Static members can be elds, properties, methods When using static members, dont need to instantiate an object
Slide 14
Static constructors must have no access modiers and cannot have any parameters
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
To declare constant members (members whose value will never change) using:
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
Slide 17
Slide 19
Contents
Review concepts in OOP Write classes in C# Interface Inheritance Polymorphism Relationships between objects
Slide 22
Inheritance (p.194)
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.)
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
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
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
Slide 27
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:
Slide 28
get { return y; }
set { y = value; } }
Slide 29
Slide 30
Slide 33
Contents
Review concepts in OOP Write classes in C# Interface Inheritance Polymorphism Relationships between objects
Slide 34
Polymorphism (p.196)
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();
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
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 {
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; } }
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 );
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
Slide 53
Collections: One class acts as a container for multiple instances (arrays of objects) of another class
Slide 54