Polymorphic support in C# Let us now examine third pillar of OOP i.e. Polymorphism.. Recall that the Employee base class defined a method named GiveBonus(),

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

OOP Abstraction Classes Class Members: Properties & Methods Instance (object) Encapsulation Interfaces Inheritance Composition Polymorphism Using Inheritance.
Object Oriented Programming
Chapter 1 Inheritance University Of Ha’il.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/George Koutsogiannakis 1.
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
More about classes and objects Classes in Visual Basic.NET.
Review of Object-Oriented Concepts in JAVA Object-Oriented Concepts supported by JAVA. Advantages of Object-Orientation. Inheritance. Abstract Classes.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Review of Object-Oriented Concepts in JAVA Object-Oriented Concepts supported by JAVA. Object-Oriented Concepts supported by JAVA. Advantages of Object-Orientation.
Inheritance and Polymorphism CS351 – Programming Paradigms.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
LECTURE 07 Programming using C# Inheritance
 Simple payroll application that polymorphically calculates the weekly pay of several different types of employees using each employee’s Earnings method.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Lecture 9 Polymorphism Richard Gesick.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Programming Pillars Introduction to Object- Oriented Programming.
Object Oriented Programming with C# Session: August-December 2009 Subject: C# Programming.
 2002 Prentice Hall. All rights reserved. 1 Introduction to Inheritance Inheritance: –1 of 3 main features of OOP –Form of software reusability –(Derived)
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Chapter 10 Inheritance and Polymorphism
Programming in Java CSCI-2220 Object Oriented Programming.
Module 10: Inheritance in C#. Overview Deriving Classes Implementing Methods Using Sealed Classes Using Interfaces Using Abstract Classes.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
JAVA Programming (Session 4) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
Inheritance ndex.html ndex.htmland “Java.
Java Inheritance in Java. Inheritance Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea.
Object-Oriented Programming: Inheritance and Polymorphism.
Object Oriented Programming Elhanan Borenstein Lecture #7.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
BY:- TOPS Technologies
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Web Design & Development Lecture 9
Chapter - 4 OOP with C# S. Nandagopalan.
Final and Abstract Classes
Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Object Oriented Programming
OOP’S Concepts in C#.Net
Review of Object-Oriented Concepts in JAVA
Java Programming Language
Interfaces.
Inheritance Inheritance is a fundamental Object Oriented concept
Review of Object-Oriented Concepts in JAVA
Abstract Classes and Interfaces
CIS 199 Final Review.
Final and Abstract Classes
Topics OOP Review Inheritance Review Abstract Classes
Programming in C# CHAPTER 5 & 6
Presentation transcript:

Polymorphic support in C# Let us now examine third pillar of OOP i.e. Polymorphism.. Recall that the Employee base class defined a method named GiveBonus(), which was implemented as follows: // Give bonus to employees. public class Employee {... public void GiveBonus(float amount) { currPay += amount; } } Because this method has been defined as public, you can now give bonuses to salespeople and managers (as well as part-time salespeople): static void Main(string[] args) { // Give each employee a bonus. Manager chucky = new Manager("Chucky", 50, 92, , " ", 9000); chucky.GiveBonus(300); chucky.DisplayStats(); SalesPerson fran = new SalesPerson("Fran", 43, 93, 3000, " ", 31); fran.GiveBonus(200); fran.DisplayStats();Console.ReadLine();}

Polymorphic support in C# The problem with the current design is that the inherited GiveBonus() method operates identically for all subclasses. Ideally, the bonus of a salesperson or part- time salesperson should take into account the number of sales. Perhaps managers should gain additional stock options in conjunction with a monetary bump in salary. How this can be solved??? Perhaps the solution may be Polymorphism….

Polymorphic support in C# The virtual and override Keywords Polymorphism provides a way for a subclass to customize how it implements a method defined by its base class. To retrofit your current design, you need to understand the meaning of the C# virtual and override keywords. If a base class wishes to define a method that may be overridden by a subclass, it must specify the method as virtual: public class Employee { // GiveBonus() has a default implementation, however // child classes are free to override this behavior. public virtual void GiveBonus(float amount) { currPay += amount; }... } When a subclass wishes to redefine a virtual method, it does so using the override keyword.

Polymorphic support in C# For example, the SalesPerson and Manager could override GiveBonus() as follows (assume that PTSalesPerson overrides GiveBonus() in manner similar to SalesPerson): public class SalesPerson : Employee { // A salesperson's bonus is influenced by the number of sales. public override void GiveBonus(float amount) { int salesBonus = 0; if(numberOfSales >= 0 && numberOfSales <= 100) salesBonus = 10; else if(numberOfSales >= 101 && numberOfSales <= 200) salesBonus = 15; else salesBonus = 20; // Anything greater than 200. base.GiveBonus (amount * salesBonus); }... } Similar in the case of Manager also…..

Polymorphic support in C# public class Manager : Employee { // Managers get some number of new stock options, in addition to raw cash. public override void GiveBonus(float amount) { // Increase salary. base.GiveBonus(amount); // And give some new stock options... Random r = new Random(); numberOfOptions += (ulong)r.Next(500); }... }

Polymorphic support in C# Notice how each overridden method is free to leverage the default behavior using the base keyword. In this way, you have no need to completely re implement the logic behind GiveBonus(), but can reuse (and possibly extend) the default behavior of the parent class. Revisiting the sealed Keyword The sealed keyword can also be applied to type members to prevent virtual members from being further overridden by derived types. This can be helpful when you do not wish to seal an entire class, just a few select methods or properties. For the sake of illustration, if we (for some reason) did wish to allow the PTSalesPerson class to be extended by other classes but make sure those classes did not further override the virtual GiveBonus(), we could write the following: // This class can be extended; // however, GiveBonus() cannot be overriden by derived classes. public class PTSalesPerson : SalesPerson {... public override sealed void GiveBonus(float amount) {... }

Polymorphic support in C# Polymorphism through abstract classes and abstract methods. How polymorphism is achieved through abstract classes and abstract methods????

Polymorphic support in C# Enforcing Polymorphic Activity: Abstract Methods When a class has been defined as an abstract base class, it may define any number of abstract members (which is analogous to a C++ pure virtual function). Abstract methods can be used whenever you wish to define a method that does not supply a default implementation. By doing so, you enforce a polymorphic trait on each descendent, leaving them to contend with the task of providing the details behind your abstract methods. To understand the role of abstract methods, let’s revisit the shapes hierarchy.

Polymorphic support in C#.

Again, to prevent the direct creation of the Shape type, you could define it as an abstract class: namespace Shapes { public abstract class Shape { // Shapes can be assigned a friendly pet name. protected string petName; // Constructors. public Shape(){ petName = "NoName"; } public Shape(string s) { petName = s;} // Draw() is virtual and may be overridden. public virtual void Draw() { Console.WriteLine("Shape.Draw()"); } public string PetName { get { return petName;} set { petName = value;} }.

Polymorphic support in C# // Circle DOES NOT override Draw(). public class Circle : Shape { public Circle() { } public Circle(string name): base(name) { } } // Hexagon DOES override Draw(). public class Hexagon : Shape { public Hexagon(){ } public Hexagon(string name): base(name) { } public override void Draw() { Console.WriteLine("Drawing {0} the Hexagon", petName); }.

Polymorphic support in C# To illustrate the full story of polymorphism, consider the following code: // Create an array of various Shapes. static void Main(string[] args) { Console.WriteLine("***** Fun with Polymorphism *****\n"); Shape[] myShapes = {new Hexagon(), new Circle(), new Hexagon("Mick"), new Circle("Beth"), new Hexagon("Linda")}; // Loop over the array and ask each object to draw itself. for(int i = 0; i < myShapes.Length; i++) myShapes[i].Draw(); Console.ReadLine(); }.

Polymorphic support in C# To understand the above code.. We need to know how the Draw() class has been converted to an abstract class and methods in it are made as abstract Note: Note: abstract methods can only be defined in abstract classes.

Polymorphic support in C# Member Hiding C# provides a facility that is the logical opposite of method overriding: member hiding. Formally speaking, if a derived class re declares an identical member inherited from a base class, the derived class has hidden (or shadowed) the parent’s member. In the real world, this possibility is the greatest when you are sub- classing from a class you (or your team) did not create yourselves (for example, if you purchase a third-party.NET software package).

Polymorphic support in C# Member Hiding assume you receive a class named ThreeDCircle from a coworker (or classmate) that currently derives from System.Object: public class ThreeDCircle { public void Draw() { Console.WriteLine("Drawing a 3D Circle"); } You figure that a ThreeDCircle “is-a” Circle, so you derive from your existing Circle type: public class ThreeDCircle : Circle { public void Draw() { Console.WriteLine("Drawing a 3D Circle"); }