Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Object Oriented Concepts Classes II
  2. 2. Object Oriented concepts <ul><li>Encapsulation </li></ul><ul><li>Composition </li></ul><ul><li>Inheritance </li></ul><ul><li>Polymorphism </li></ul>
  3. 3. Encapsulation <ul><li>Classes normally hide the details of their implementation from their clients. This is called information hiding . </li></ul><ul><li>The client cares about what functionality a class offers, not about how that functionality is implemented. This concept is referred to as data abstraction . </li></ul><ul><li>C# provides this object oriented concept with properties . </li></ul>
  4. 4. Composition <ul><li>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 </li></ul><ul><li>One form of software reuse is composition </li></ul><ul><li>Example: Employee object using Date object for hire date </li></ul><ul><ul><li>See composition.cs </li></ul></ul>
  5. 5. Inheritance <ul><li>Another form of software reuse is inheritance </li></ul><ul><li>Inheritance allows a new class to absorb an existing class’s members. </li></ul><ul><li>A derived class normally adds its own fields and methods to represent a more specialized group of objects. </li></ul><ul><li>The is-a relationship represents inheritance. </li></ul><ul><li>Examples: </li></ul><ul><li>Base class Derived classes </li></ul><ul><li>Student GraduateStudent, UndergraduateStudent </li></ul><ul><li>Shape Circle, Triangle, Rectangle </li></ul><ul><li>Loan CarLoan, HomeImprovementLoan, MortgageLoan </li></ul><ul><li>Employee Faculty, Staff, HourlyWorker, CommissionWorker </li></ul><ul><li>BankAccount CheckingAccount, SavingsAccount </li></ul>
  6. 6. Example <ul><li>CommissionEmployee represents an employee who is paid a percentage of their sales. </li></ul><ul><li>BasePlusCommissionEmployee class represents an employee that receives a base salary in addition to a commission. </li></ul><ul><li>BasePlusCommissionEmployee </li></ul>
  7. 7. Base and Derived Classes in C# <ul><li>Objects of all classes that extend a common base class can be treated as objects of that base class. </li></ul><ul><li>A base class’s private members are not directly accessible by derived-class methods and properties. </li></ul><ul><li>A base class’s protected members can be accessed by members of both that base class and of its derived classes. </li></ul><ul><li>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. </li></ul><ul><li>If a class does not specify that it inherits from another class, it implicitly inherits from object . </li></ul><ul><ul><li>public class CommissionEmployee : object </li></ul></ul>
  8. 8. Base and Derived Classes in C# <ul><li>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 . </li></ul><ul><ul><ul><li>public override string ToString() </li></ul></ul></ul><ul><li>A constructor initializer with keyword base invokes the base-class constructor. </li></ul><ul><ul><li>See example BasePlusCommissionEmployee </li></ul></ul><ul><li>The virtual and abstract keywords are required in a base-class method so that the derived classes can override it. </li></ul><ul><ul><ul><li>See example BasePlusCommissionEmployee </li></ul></ul></ul><ul><li>Using protected instance variables creates several potential problems. </li></ul><ul><ul><li>The derived-class object can set an inherited variable’s value directly without validity checking. </li></ul></ul><ul><ul><li>Derived-class methods would need to be written to depend on the base class’s data implementation. </li></ul></ul><ul><li>You should be able to change the base-class implementation while still providing the same services to the derived classes. </li></ul>
  9. 9. Base and Derived Classes in C# <ul><li>The derived-class constructor, before performing its own tasks, invokes its direct base class’s constructor. </li></ul><ul><li>This is done either explicitly or implicitly. </li></ul><ul><li>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. </li></ul><ul><li>public override decimal Earnings() </li></ul><ul><li>{ </li></ul><ul><li>return BaseSalary + base. Earnings(); </li></ul><ul><li>} // end method Earnings </li></ul>
  10. 10. System.Object <ul><li>All classes inherit directly or indirectly from the object class. </li></ul><ul><li>Figure below summarizes object’s methods: </li></ul>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. 11. Polymorphism <ul><li>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. </li></ul><ul><li>If class Rectangle is derived from class Quadrilateral , then a Rectangle is a more specific version of a Quadrilateral . </li></ul><ul><li>Any operation that can be performed on a Quadrilateral object can also be performed on a Rectangle object. </li></ul><ul><li>These operations also can be performed on other Quadrilaterals , such as Squares , Parallelograms and Trapezoids . </li></ul><ul><li>The polymorphism occurs when an application invokes a method through a base-class variable. </li></ul>
  12. 12. Polymorphism <ul><li>An object of a derived class can be treated as an object of its base class. </li></ul><ul><li>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 . </li></ul><ul><li>At execution time, the type of the object to which the variable refers determines the actual method to use. </li></ul><ul><li>See example: polymorphism </li></ul><ul><li>virtual , override and new keywords </li></ul><ul><ul><li> </li></ul></ul>
  13. 13. Case Study: Payroll System Using Polymorphism <ul><li>In this example, we create an enhanced employee hierarchy to solve the following problem: </li></ul><ul><li>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. </li></ul>
  14. 14. Payroll System Using Polymorphism <ul><li>We use abstract class Employee to represent the general concept of an employee. </li></ul><ul><li>SalariedEmployee , CommissionEmployee and HourlyEmployee extend Employee . </li></ul><ul><li>Class BasePlusCommissionEmployee —which extends CommissionEmployee —represents the last employee type. </li></ul><ul><li>Let’s look at the example code: PayrollSystem solution </li></ul>Figure | Employee hierarchy UML class diagram
  15. 15. Abstract Classes <ul><li>Abstract classes , or abstract base classes cannot be used to instantiate objects. </li></ul><ul><li>Abstract base classes are too general to create real objects—they specify only what is common among derived classes. </li></ul><ul><li>Classes that can be used to instantiate objects are called concrete classes . </li></ul><ul><li>Concrete classes provide the specifics that make it reasonable to instantiate objects. </li></ul><ul><li>An abstract class normally contains one or more abstract methods , which have the keyword abstract in their declaration. </li></ul><ul><li>A class that contains abstract methods must be declared as an abstract class even if it contains concrete (nonabstract) methods. </li></ul><ul><li>Abstract methods do not provide implementations. </li></ul><ul><li>Constructors and static methods cannot be declared abstract . </li></ul>
  16. 16. Abstract Classes <ul><li>abstract property declarations have the form: </li></ul><ul><ul><li>public abstract PropertyType MyProperty </li></ul></ul><ul><ul><li>{ get ; set ; </li></ul></ul><ul><ul><li>} // end abstract property </li></ul></ul><ul><li>An abstract property may omit implementations for the get accessor, the set accessor or both. </li></ul><ul><li>Concrete derived classes must provide implementations for every accessor declared in the abstract property. </li></ul>
  17. 17. as / is operators <ul><li>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. </li></ul><ul><li>You can avoid a potential InvalidCastException by using the as operator to do a downcast rather than a cast operator. </li></ul><ul><ul><li>If the downcast is invalid , the expression will be null instead of throwing an exception. </li></ul></ul><ul><li>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. </li></ul>
  18. 18. Interfaces <ul><li>Interfaces define and standardize the ways in which people and systems can interact with one another. </li></ul><ul><li>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. </li></ul><ul><li>An interface declaration begins with the keyword interface and can contain only abstract methods, properties, indexers and events. </li></ul><ul><li>All interface members are implicitly declared both public and abstract . </li></ul><ul><li>An interface can extend one or more other interfaces to create a more elaborate interface that other classes can implement. </li></ul>
  19. 19. Interfaces <ul><li>An interface is typically used when disparate (i.e., unrelated) classes need to share common methods so that they can be processed polymorphically </li></ul><ul><li>A programmer can create an interface that describes the desired functionality, then implement this interface in any classes requiring that functionality. </li></ul><ul><li>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. </li></ul><ul><li>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. </li></ul>
  20. 20. Interface Example: IPayable <ul><li>To build an application that can determine payments for employees and invoices alike, we first create an interface named IPayable . </li></ul><ul><li>Interface IPayable contains method GetPaymentAmount that returns a decimal amount to be paid for an object of any class that implements the interface. </li></ul><ul><li>By convention, the name of an interface begins with &quot;I&quot; . This helps distinguish interfaces from classes, improving code readability. </li></ul><ul><li>When a class implements an interface, the same is-a relationship provided by inheritance applies. </li></ul><ul><li>Example: IPayable solution </li></ul>
  21. 21. Multiple Inheritance <ul><li>Not supported in classes, but supported via interfaces </li></ul><ul><li>To implement more than one interface, use a comma-separated list of interface names after the colon (:) in the class declaration. </li></ul><ul><li>Example: </li></ul><ul><ul><li>public abstract class Array : </li></ul></ul><ul><ul><li>ICloneable, IList, ICollection, IEnumerable </li></ul></ul>
  22. 22. Common Interfaces of the .NET Framework Class Library
  23. 23. sealed Methods and Classes <ul><li>A method declared sealed in a base class cannot be overridden in a derived class. </li></ul><ul><li>Methods that are declared private are implicitly sealed . </li></ul><ul><li>Methods that are declared static also are implicitly sealed , because static methods cannot be overridden either. </li></ul><ul><li>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. </li></ul>
  24. 24. this <ul><li>public class SimpleTime </li></ul><ul><li>{ </li></ul><ul><li>private int hour; // 0-23 </li></ul><ul><li>private int minute; // 0-59 </li></ul><ul><li>private int second; // 0-59 </li></ul><ul><li>// if the constructor uses parameter names identical to </li></ul><ul><li>// instance variable names the &quot;this&quot; reference is </li></ul><ul><li>// required to distinguish between names </li></ul><ul><li>public SimpleTime( int hour, int minute, int second ) </li></ul><ul><li>{ </li></ul><ul><li>this. hour = hour; // set &quot;this&quot; object's hour // instance variable </li></ul><ul><li>this. minute = minute; // set &quot;this&quot; object's minute </li></ul><ul><li>this. second = second; // set &quot;this&quot; object's second </li></ul><ul><li>} </li></ul>
  25. 25. Overloaded Constructors & this <ul><li>public class Time2 </li></ul><ul><li>{ </li></ul><ul><li>private int hour; // 0 - 23 </li></ul><ul><li>private int minute; // 0 - 59 </li></ul><ul><li>private int second; // 0 - 59 </li></ul><ul><li>// Time2 no-argument constructor </li></ul><ul><li> public Time2() : this ( 0, 0, 0 ) { } </li></ul><ul><li>// Time2 constructor: hour supplied, minute & second defaulted to 0 </li></ul><ul><li>public Time2( int h ) : this ( h, 0, 0 ) { } </li></ul><ul><li>// Time2 constructor: hour & minute supplied, second defaulted to 0 </li></ul><ul><li>public Time2( int h, int m ) : this ( h, m, 0 ) { } </li></ul><ul><li>// Time2 constructor: hour, minute and second supplied </li></ul><ul><li>public Time2( int h, int m, int s ) </li></ul><ul><li>{ SetTime( h, m, s ); // invoke SetTime to validate time </li></ul><ul><li>} </li></ul>
  26. 26. Destructors <ul><li>A destructor’s name is the class name, preceded by a tilde, and it has no access modifier in its header. </li></ul><ul><ul><li>public class GradeBook </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> // constructor </li></ul></ul><ul><ul><li> public GradeBook(string name) </li></ul></ul><ul><ul><li>{ courseName = name; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li> // destructor </li></ul></ul><ul><ul><li>~ GradeBook() </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>The destructor is invoked by the garbage collector to perform termination housekeeping before its memory is reclaimed. </li></ul><ul><li>Many FCL classes provide Close or Dispose methods for cleanup. </li></ul>