Object Oriented Concepts Classes II
Object Oriented concepts Encapsulation Composition Inheritance Polymorphism
Encapsulation Classes normally hide the details of their implementation from their clients. This is called  information hiding . The client cares about what functionality a class offers, not about how that functionality is implemented. This concept is referred to as  data abstraction . C# provides this object oriented concept with  properties .
Composition A class can have references to objects of other classes as members. This is called  composition  and is sometimes referred to as a  has-a   relationship   One form of software reuse is composition Example: Employee object using Date object for hire date See  composition.cs
Inheritance Another form of software reuse is inheritance Inheritance  allows a new class to absorb an existing class’s members. A derived class normally adds its own fields and methods to represent a more specialized group of objects. The  is-a   relationship  represents inheritance. Examples: Base class Derived classes Student GraduateStudent, UndergraduateStudent Shape Circle, Triangle, Rectangle Loan CarLoan, HomeImprovementLoan, MortgageLoan Employee Faculty, Staff, HourlyWorker, CommissionWorker BankAccount CheckingAccount, SavingsAccount
Example CommissionEmployee  represents an employee who is paid a percentage of their sales. BasePlusCommissionEmployee  class represents an employee that receives a base salary in addition to a commission. BasePlusCommissionEmployee
Base and Derived Classes in C# Objects of all classes that extend a common base class can be treated as objects of that base class. A base class’s  private  members are not directly accessible by derived-class methods and properties. A base class’s  protected  members can be accessed by members of both that base class  and  of its derived classes. A base class’s  protected   internal   members can be accessed by members of a base class, the derived classes  and  by any class in the same assembly. If a class does not specify that it inherits from another class, it implicitly inherits from  object . public class CommissionEmployee  : object
Base and Derived Classes in C# The derived class can  override  the base-class method. To override a base-class method, a derived class must declare a method with keyword   override  . public  override  string ToString() A constructor initializer with keyword  base  invokes the base-class constructor. See example  BasePlusCommissionEmployee The  virtual  and  abstract  keywords are required in a base-class method so that the derived classes can override it. See example  BasePlusCommissionEmployee Using  protected  instance variables creates several potential problems. The derived-class object can set an inherited variable’s value directly without validity checking. Derived-class methods would need to be written to depend on the base class’s data implementation. You should be able to change the base-class implementation while still providing the same services to the derived classes.
Base and Derived Classes in C# The derived-class constructor, before performing its own tasks, invokes its direct base class’s constructor. This is done either explicitly or implicitly. When a base-class method is overridden in a derived class, if the derived-class version wants to call the base-class version, it uses  base  keyword. public override decimal Earnings() { return BaseSalary +  base. Earnings(); } // end method Earnings
System.Object All classes inherit directly or indirectly from the object class. Figure below summarizes object’s methods: Method Description Equals This method compares two objects for equality and returns true if they are equal and false otherwise.  Finalize Finalize is called by the garbage collector before it reclaims an object’s memory. GetHashCode The hashcode value returned can be used by a hashtable to determine the location at which to insert the corresponding value. GetType Returns an object of class Type that contains information about the object’s type.  MemberwiseClone This protected method makes a copy of the object on which it is called. Instance-variable values in one object are copied into another object of the same type. For reference types, only the references are copied. ReferenceEquals This static method returns true if two objects are the same instance or if they are null references. ToString Returns a string representation of an object. The default implementation returns the namespace and class name.
Polymorphism Polymorphism  enables you to write applications that process objects that share the same base class in a class hierarchy as if they were all objects of the base class. If class  Rectangle  is derived from class  Quadrilateral , then a  Rectangle  is a more specific version of a  Quadrilateral . Any operation that can be performed on a  Quadrilateral  object can also be performed on a  Rectangle  object. These operations also can be performed on other  Quadrilaterals , such as  Squares ,  Parallelograms  and  Trapezoids . The polymorphism occurs when an application invokes a method through a base-class variable.
Polymorphism An object of a derived class can be treated as an object of its base class. When the compiler encounters a method call made through a variable, it determines if the method can be called by checking the  variable’s class type . At execution time,  the type of the object to which the variable refers   determines the actual method to use.   See example:  polymorphism virtual ,  override  and  new  keywords http://msdn.microsoft.com/en-us/library/6fawty39(VS.80).aspx
Case Study: Payroll System Using Polymorphism In this example, we create an enhanced employee hierarchy to  solve the following problem: A company pays its employees on a weekly basis. The employees are of four types: Salaried employees are paid a fixed weekly salary regardless of the number of hours worked, hourly employees are paid by the hour and receive overtime pay for all hours worked in excess of 40 hours, commission employees are paid a percentage of their sales, and salaried-commission employees receive a base salary plus a percentage of their sales. For the current pay period, the company has decided to reward salaried-commission employees by adding 10% to their base salaries.
Payroll System Using Polymorphism We use  abstract  class  Employee  to represent the general concept of an employee. SalariedEmployee ,  CommissionEmployee  and  HourlyEmployee  extend  Employee . Class  BasePlusCommissionEmployee —which extends  CommissionEmployee —represents  the last employee type. Let’s look at the example code:  PayrollSystem  solution Figure  |  Employee  hierarchy UML class diagram
Abstract Classes Abstract classes , or  abstract base classes  cannot be used to instantiate objects. Abstract base classes are too general to create real objects—they specify only what is common among derived classes. Classes that can be used to instantiate objects are called  concrete classes .  Concrete classes provide the specifics that make it reasonable to instantiate objects. An abstract class normally contains one or more  abstract methods , which have the keyword abstract in their declaration. A class that contains  abstract  methods must be declared as an  abstract  class even if it contains concrete (nonabstract) methods. Abstract  methods do not provide implementations. Constructors and static methods cannot be declared  abstract  .
Abstract Classes abstract property declarations have the form: public abstract  PropertyType  MyProperty {   get ;   set ; }  // end abstract property An abstract property may omit implementations for the  get  accessor, the  set  accessor or both. Concrete derived classes must provide implementations for  every  accessor declared in the abstract property.
as / is  operators When downcasting an object, a  System.InvalidCastException  occurs if at execution time the object does not have an  is-a relationship  with the type specified in the cast operator. An object can be cast only to its own type or to the type of one of its base classes. You can avoid a potential  InvalidCastException  by using the  as   operator to do a downcast rather than a cast operator. If the downcast is  invalid , the expression will be  null  instead of throwing an exception. Before performing a cast from a base-class object to a derived-class object, use the   is   operator to ensure that the object is indeed an object of an appropriate derived-class type.
Interfaces Interfaces  define and standardize the ways in which people and systems can interact with one another.  A C#  interface  describes a set of methods that can be called on an object—to tell it, for example, to perform some task or return some piece of information.  An  interface declaration  begins with the keyword interface and can contain only abstract methods, properties, indexers and events. All interface members are implicitly declared both  public  and  abstract . An interface can extend one or more other interfaces to create a more elaborate interface that other classes can implement.
Interfaces An interface is typically used when disparate (i.e., unrelated) classes need to share  common  methods so that they can be processed  polymorphically A programmer can create an interface that  describes  the desired functionality, then implement this interface in any classes requiring that functionality. An interface often is used in place of an  abstract  class when there is no default implementation to inherit—that is, no fields and no default method implementations. Like abstract classes, interfaces are typically public types, so they are normally declared in files by themselves with the same name as the interface and the .cs file-name extension.
Interface Example:  IPayable To build an application that can determine payments for employees and invoices alike, we first create an interface named  IPayable . Interface  IPayable   contains method  GetPaymentAmount  that returns a decimal amount to be paid for an object of any class that implements the interface. By convention, the name of an interface begins with  "I" . This helps distinguish interfaces from classes, improving code readability. When a class implements an interface, the same  is-a  relationship  provided by inheritance applies. Example:  IPayable  solution
Multiple Inheritance Not supported in classes, but supported via interfaces To implement more than one interface, use a comma-separated list of interface names after the colon (:) in the class declaration. Example:  public abstract class Array :  ICloneable, IList, ICollection, IEnumerable
Common Interfaces of the .NET Framework Class Library
sealed  Methods and Classes A method declared  sealed  in a base class cannot be overridden in a derived class. Methods that are declared  private  are implicitly  sealed . Methods that are declared  static  also are implicitly  sealed , because  static  methods cannot be overridden either. A derived-class method declared both  override  and  sealed  can override a base-class method, but cannot be overridden in classes further down the inheritance hierarchy.
this public class SimpleTime { private int hour;  // 0-23 private int minute; // 0-59 private int second; // 0-59  // if the constructor uses parameter names identical to  // instance variable names the "this" reference is  // required to distinguish between names public SimpleTime( int hour, int minute, int second ) { this. hour = hour;  // set "this" object's hour  // instance variable this. minute = minute; // set "this" object's minute this. second = second; // set "this" object's second }
Overloaded Constructors &  this public class Time2 { private int hour;  // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 // Time2 no-argument constructor   public Time2() :  this ( 0, 0, 0 ) { } // Time2 constructor: hour supplied, minute & second defaulted to 0 public Time2( int h ) :  this ( h, 0, 0 ) { } // Time2 constructor: hour & minute supplied, second defaulted to 0 public Time2( int h, int m ) :  this ( h, m, 0 ) { } // Time2 constructor: hour, minute and second supplied public Time2( int h, int m, int s ) { SetTime( h, m, s ); // invoke SetTime to validate time }
Destructors A destructor’s name is the class name, preceded by a tilde, and it has no access modifier in its header. public class GradeBook {   // constructor   public GradeBook(string name) {  courseName = name; }   // destructor ~ GradeBook() { } } The  destructor  is invoked by the garbage collector to perform  termination housekeeping  before its memory is reclaimed. Many FCL classes provide Close or Dispose methods for cleanup.

Classes2

  • 1.
  • 2.
    Object Oriented conceptsEncapsulation Composition Inheritance Polymorphism
  • 3.
    Encapsulation Classes normallyhide the details of their implementation from their clients. This is called information hiding . The client cares about what functionality a class offers, not about how that functionality is implemented. This concept is referred to as data abstraction . C# provides this object oriented concept with properties .
  • 4.
    Composition A classcan have references to objects of other classes as members. This is called composition and is sometimes referred to as a has-a relationship One form of software reuse is composition Example: Employee object using Date object for hire date See composition.cs
  • 5.
    Inheritance Another formof software reuse is inheritance Inheritance allows a new class to absorb an existing class’s members. A derived class normally adds its own fields and methods to represent a more specialized group of objects. The is-a relationship represents inheritance. Examples: Base class Derived classes Student GraduateStudent, UndergraduateStudent Shape Circle, Triangle, Rectangle Loan CarLoan, HomeImprovementLoan, MortgageLoan Employee Faculty, Staff, HourlyWorker, CommissionWorker BankAccount CheckingAccount, SavingsAccount
  • 6.
    Example CommissionEmployee represents an employee who is paid a percentage of their sales. BasePlusCommissionEmployee class represents an employee that receives a base salary in addition to a commission. BasePlusCommissionEmployee
  • 7.
    Base and DerivedClasses in C# Objects of all classes that extend a common base class can be treated as objects of that base class. A base class’s private members are not directly accessible by derived-class methods and properties. A base class’s protected members can be accessed by members of both that base class and of its derived classes. A base class’s protected internal members can be accessed by members of a base class, the derived classes and by any class in the same assembly. If a class does not specify that it inherits from another class, it implicitly inherits from object . public class CommissionEmployee : object
  • 8.
    Base and DerivedClasses in C# The derived class can override the base-class method. To override a base-class method, a derived class must declare a method with keyword override . public override string ToString() A constructor initializer with keyword base invokes the base-class constructor. See example BasePlusCommissionEmployee The virtual and abstract keywords are required in a base-class method so that the derived classes can override it. See example BasePlusCommissionEmployee Using protected instance variables creates several potential problems. The derived-class object can set an inherited variable’s value directly without validity checking. Derived-class methods would need to be written to depend on the base class’s data implementation. You should be able to change the base-class implementation while still providing the same services to the derived classes.
  • 9.
    Base and DerivedClasses in C# The derived-class constructor, before performing its own tasks, invokes its direct base class’s constructor. This is done either explicitly or implicitly. When a base-class method is overridden in a derived class, if the derived-class version wants to call the base-class version, it uses base keyword. public override decimal Earnings() { return BaseSalary + base. Earnings(); } // end method Earnings
  • 10.
    System.Object All classesinherit directly or indirectly from the object class. Figure below summarizes object’s methods: Method Description Equals This method compares two objects for equality and returns true if they are equal and false otherwise. Finalize Finalize is called by the garbage collector before it reclaims an object’s memory. GetHashCode The hashcode value returned can be used by a hashtable to determine the location at which to insert the corresponding value. GetType Returns an object of class Type that contains information about the object’s type. MemberwiseClone This protected method makes a copy of the object on which it is called. Instance-variable values in one object are copied into another object of the same type. For reference types, only the references are copied. ReferenceEquals This static method returns true if two objects are the same instance or if they are null references. ToString Returns a string representation of an object. The default implementation returns the namespace and class name.
  • 11.
    Polymorphism Polymorphism enables you to write applications that process objects that share the same base class in a class hierarchy as if they were all objects of the base class. If class Rectangle is derived from class Quadrilateral , then a Rectangle is a more specific version of a Quadrilateral . Any operation that can be performed on a Quadrilateral object can also be performed on a Rectangle object. These operations also can be performed on other Quadrilaterals , such as Squares , Parallelograms and Trapezoids . The polymorphism occurs when an application invokes a method through a base-class variable.
  • 12.
    Polymorphism An objectof a derived class can be treated as an object of its base class. When the compiler encounters a method call made through a variable, it determines if the method can be called by checking the variable’s class type . At execution time, the type of the object to which the variable refers determines the actual method to use. See example: polymorphism virtual , override and new keywords http://msdn.microsoft.com/en-us/library/6fawty39(VS.80).aspx
  • 13.
    Case Study: PayrollSystem Using Polymorphism In this example, we create an enhanced employee hierarchy to solve the following problem: A company pays its employees on a weekly basis. The employees are of four types: Salaried employees are paid a fixed weekly salary regardless of the number of hours worked, hourly employees are paid by the hour and receive overtime pay for all hours worked in excess of 40 hours, commission employees are paid a percentage of their sales, and salaried-commission employees receive a base salary plus a percentage of their sales. For the current pay period, the company has decided to reward salaried-commission employees by adding 10% to their base salaries.
  • 14.
    Payroll System UsingPolymorphism We use abstract class Employee to represent the general concept of an employee. SalariedEmployee , CommissionEmployee and HourlyEmployee extend Employee . Class BasePlusCommissionEmployee —which extends CommissionEmployee —represents the last employee type. Let’s look at the example code: PayrollSystem solution Figure | Employee hierarchy UML class diagram
  • 15.
    Abstract Classes Abstractclasses , or abstract base classes cannot be used to instantiate objects. Abstract base classes are too general to create real objects—they specify only what is common among derived classes. Classes that can be used to instantiate objects are called concrete classes . Concrete classes provide the specifics that make it reasonable to instantiate objects. An abstract class normally contains one or more abstract methods , which have the keyword abstract in their declaration. A class that contains abstract methods must be declared as an abstract class even if it contains concrete (nonabstract) methods. Abstract methods do not provide implementations. Constructors and static methods cannot be declared abstract .
  • 16.
    Abstract Classes abstractproperty declarations have the form: public abstract PropertyType MyProperty { get ; set ; } // end abstract property An abstract property may omit implementations for the get accessor, the set accessor or both. Concrete derived classes must provide implementations for every accessor declared in the abstract property.
  • 17.
    as / is operators When downcasting an object, a System.InvalidCastException occurs if at execution time the object does not have an is-a relationship with the type specified in the cast operator. An object can be cast only to its own type or to the type of one of its base classes. You can avoid a potential InvalidCastException by using the as operator to do a downcast rather than a cast operator. If the downcast is invalid , the expression will be null instead of throwing an exception. Before performing a cast from a base-class object to a derived-class object, use the is operator to ensure that the object is indeed an object of an appropriate derived-class type.
  • 18.
    Interfaces Interfaces define and standardize the ways in which people and systems can interact with one another. A C# interface describes a set of methods that can be called on an object—to tell it, for example, to perform some task or return some piece of information. An interface declaration begins with the keyword interface and can contain only abstract methods, properties, indexers and events. All interface members are implicitly declared both public and abstract . An interface can extend one or more other interfaces to create a more elaborate interface that other classes can implement.
  • 19.
    Interfaces An interfaceis typically used when disparate (i.e., unrelated) classes need to share common methods so that they can be processed polymorphically A programmer can create an interface that describes the desired functionality, then implement this interface in any classes requiring that functionality. An interface often is used in place of an abstract class when there is no default implementation to inherit—that is, no fields and no default method implementations. Like abstract classes, interfaces are typically public types, so they are normally declared in files by themselves with the same name as the interface and the .cs file-name extension.
  • 20.
    Interface Example: IPayable To build an application that can determine payments for employees and invoices alike, we first create an interface named IPayable . Interface IPayable contains method GetPaymentAmount that returns a decimal amount to be paid for an object of any class that implements the interface. By convention, the name of an interface begins with "I" . This helps distinguish interfaces from classes, improving code readability. When a class implements an interface, the same is-a relationship provided by inheritance applies. Example: IPayable solution
  • 21.
    Multiple Inheritance Notsupported in classes, but supported via interfaces To implement more than one interface, use a comma-separated list of interface names after the colon (:) in the class declaration. Example: public abstract class Array : ICloneable, IList, ICollection, IEnumerable
  • 22.
    Common Interfaces ofthe .NET Framework Class Library
  • 23.
    sealed Methodsand Classes A method declared sealed in a base class cannot be overridden in a derived class. Methods that are declared private are implicitly sealed . Methods that are declared static also are implicitly sealed , because static methods cannot be overridden either. A derived-class method declared both override and sealed can override a base-class method, but cannot be overridden in classes further down the inheritance hierarchy.
  • 24.
    this public classSimpleTime { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 // if the constructor uses parameter names identical to // instance variable names the "this" reference is // required to distinguish between names public SimpleTime( int hour, int minute, int second ) { this. hour = hour; // set "this" object's hour // instance variable this. minute = minute; // set "this" object's minute this. second = second; // set "this" object's second }
  • 25.
    Overloaded Constructors & this public class Time2 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 // Time2 no-argument constructor public Time2() : this ( 0, 0, 0 ) { } // Time2 constructor: hour supplied, minute & second defaulted to 0 public Time2( int h ) : this ( h, 0, 0 ) { } // Time2 constructor: hour & minute supplied, second defaulted to 0 public Time2( int h, int m ) : this ( h, m, 0 ) { } // Time2 constructor: hour, minute and second supplied public Time2( int h, int m, int s ) { SetTime( h, m, s ); // invoke SetTime to validate time }
  • 26.
    Destructors A destructor’sname is the class name, preceded by a tilde, and it has no access modifier in its header. public class GradeBook { // constructor public GradeBook(string name) { courseName = name; } // destructor ~ GradeBook() { } } The destructor is invoked by the garbage collector to perform termination housekeeping before its memory is reclaimed. Many FCL classes provide Close or Dispose methods for cleanup.