Download presentation
1
Object Oriented Concepts
Classes II Object Oriented Concepts
2
Object Oriented concepts
Encapsulation Composition Inheritance Polymorphism
3
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.
4
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
5
Inheritance Base class Derived classes
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
6
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
7
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. 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.
8
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
9
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.
10
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.
11
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
12
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.
13
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 .
14
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.
15
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.
16
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
17
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.
18
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.
19
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
20
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
21
Common Interfaces of the .NET Framework Class Library
22
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.
23
Operator Overloading Just like methods, we can override operators to give them new meanings (e.g. + addition) We use the operator keyword Operator methods need to be static Operator methods need to take at least one parameter Operator methods could be overloaded too (multiple operator methods can exist) Let’s see an example: ComplexNumber
24
Extension Methods Used to add functionality to an existing class without modifying the class’s source code. See example ExtensionMethods.sln The this keyword before a method’s first parameter notifies the compiler that the method extends an existing class. An extension method is called on an object of the class that it extends as if it were a members of the class. The compiler implicitly passes the object that is used to call the method as the extension method’s first argument. The type of an extension method’s first parameter specifies the class that is being extended—extension methods must define at least one parameter. Extension methods must be defined as static methods in a static top-level class.
25
struct (structure) struct is very similar to a class
Like classes, struct’s can have methods and properties with access modifiers. Struct members are accessed via (.) operator similarly. So they are almost the same with one difference: Class is a reference type whereas struct is a value type. Example: mystruct.cs
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.