Programming With Java ICS 201 1 Chapter 8 Polymorphism.

Slides:



Advertisements
Similar presentations
Chapter 15 Polymorphism and Virtual Functions. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Virtual Function.
Advertisements

Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 4 : Polymorphism King Fahd University of Petroleum & Minerals College of Computer.
A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CMSC 202 Inheritance. Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
© 2006 Pearson Addison-Wesley. All rights reserved8-1 The final Modifier A method marked final indicates that it cannot be overridden with a new definition.
Chapter 8 Polymorphism and Abstract Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS102--Object Oriented Programming Lecture 9: – Polymorphism Copyright © 2008 Xiaoyan Li.
1 Lecture 4 Further OO Concepts I - Polymorphism Overview  What is polymorphism?  Why polymorphism is wonderful?  Why is Upcasting useful?  What is.
Slides prepared by Rose Williams, Binghamton University Chapter 8 Polymorphism Part I.
Creating Classes from Other Classes Chapter 2. 2 Chapter Contents Composition Adapters Inheritance Invoking constructors from within constructors Private.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
CS102--Object Oriented Programming Lecture 10: – Abstract Classes Copyright © 2008 Xiaoyan Li.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
Chapter 8 Polymorphism and Abstract Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
10 Polymorphism. 2 Contents Defining Polymorphism Method Overloading Method Overriding Early Binding and Late Binding Implementing Polymorphism.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Chapter -6 Polymorphism
© 2004 Pearson Addison-Wesley. All rights reserved April 14, 2006 Polymorphism ComS 207: Programming I (in Java) Iowa State University, SPRING 2006 Instructor:
Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Peyman Dodangeh Sharif University of Technology Fall 2014.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Programming With Java ICS201 University Of Ha’il1 ICS 201 Introduction to Computer Science Inheritance.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Modern Programming Tools And Techniques-I
Polymorphism and Abstract Classes
Advanced Programming in Java
Inheritance and Polymorphism
Comp 249 Programming Methodology
ATS Application Programming: Java Programming
CS 302 Week 11 Jim Williams, PhD.
Computer Science II Exam 1 Review.
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
CMSC 202 Polymorphism.
Classes, Encapsulation, Methods and Constructors (Continued)
Java Inheritance.
Polymorphism.
CIS 199 Final Review.
Java Programming: From the Ground Up
Advanced Programming in Java
Presentation transcript:

Programming With Java ICS Chapter 8 Polymorphism

Programming With Java ICS 201 Object-Oriented Concept  Object & Class  Encapsulation  Inheritance  Polymorphism 2

Programming With Java ICS Polymorphism  polymorphism: many forms

Programming With Java ICS Polymorphism  Polymorphism (from the Greek, meaning "many forms", or something similar)  The mechanism by which several methods can have the same name and implement the same abstract operation. Requires that there be multiple methods of the same name The choice of which one to execute depends on the object that is in a variable Reduces the need for programmers to code many if- else or switch statements

Programming With Java ICS 201 Polymorphism DrawChart DrawChart(1) DrawChart(1,2,1,2) DrawChart(1,1,1) DrawTriangle(1,1,1) DrawRect(1,2,1,2) DrawCircle(1) 5

Programming With Java ICS Polymorphism Example

Programming With Java ICS 201 Polymorphism  Add(integer, integer)  Add(string, string)  Add(string, integer) Add(1,1)  2 Add(“Hello”, “World”)  “HelloWorld” Add(“Hello”, 2)  “Hello2” 7

Programming With Java ICS 201 Polymorphism :PaySlip :HourlyPaidEmployee :WeeklyPaidEmployee :MonthlyPaidEmployee  getTotalPay() calculatePay() 8

Programming With Java ICS 201 Which bill() version ? Which bill() versions ? Introductory example to Polymorphism

Programming With Java ICS Polymorphism  Methods can be overloaded. A method has the same name as another member methods, but the type and/or the count of parameters differs. class Integer { float val; void add( int amount ) { val = val + amount; } void add( int num, int den) { val = float(num) / den; }

Programming With Java ICS Polymorphism  Polymorphism is the ability to associate many meanings to one method name  It does this through a special mechanism known as late binding or dynamic binding  Inheritance allows a base class to be defined, and other classes derived from it  Code for the base class can then be used for its own objects, as well as objects of any derived classes  Polymorphism allows changes to be made to method definitions in the derived classes.

Programming With Java ICS Late Binding  The process of associating a method definition with a method invocation is called binding.  If the method definition is associated with its call when the code is compiled, that is called early binding.  If the method definition is associated with its call when the method is invoked (at run time), that is called late binding or dynamic binding.

Programming With Java ICS The Sale and DiscountSale Classes  The Sale class contains two instance variables  name: the name of an item (String)  price: the price of an item (double)  It contains two constructors  A no-argument constructor that sets name to "No name yet", and price to 0.0  A two-parameter constructor that takes in a String (for name) and a double (for price)

Programming With Java ICS The Sale and DiscountSale Classes  The Sale class also has a set of accessors (getName, getPrice), mutators (setName, setPrice), overridden methods equals and toString a static announcement method. a method bill, that determines the bill for a sale, which simply returns the price of the item. It has also two methods, equalDeals and lessThan, each of which compares two sale objects by comparing their bills and returns a boolean value.

Programming With Java ICS The Sale and DiscountSale Classes  The DiscountSale class inherits the instance variables and methods from the Sale class.  In addition, it has its own instance variable, discount (a percent of the price),  it has also its own suitable constructor methods,  accessor method (getDiscount),  mutator method (setDiscount),  overriden toString method, and static announcement method.  It has also its own bill method which computes the bill as a function of the discount and the price.

Programming With Java ICS 201 The Sale and DiscountSale Classes  The Sale class lessThan method Note the bill() method invocations: public boolean lessThan (Sale otherSale) { if (otherSale == null) { System.out.println("Error:null object"); System.exit(0); } return (bill( ) < otherSale.bill( )); }

Programming With Java ICS 201 The Sale and DiscountSale Classes  The Sale class bill() method: public double bill( ) { return price; }  The DiscountSale class bill() method: public double bill( ) { double fraction = discount/100; return (1 - fraction) * getPrice( ); }

Programming With Java ICS The Sale and DiscountSale Classes  Given the following in a program:... Sale simple = new sale(“xx", 10.00); DiscountSale discount = new DiscountSale(“xx", 11.00, 10);... if (discount.lessThan(simple)) System.out.println("$" + discount.bill() + " < " + "$" + simple.bill() + " because late-binding works!");...  Output would be: $9.90 < $10 because late-binding works!

Programming With Java ICS The Sale and DiscountSale Classes  In the previous example, the boolean expression in the if statement returns true.  As the output indicates, when the lessThan method in the Sale class is executed, it knows which bill() method to invoke  The DiscountSale class bill() method for discount, and the Sale class bill() method for simple.  Note that when the Sale class was created and compiled, the DiscountSale class and its bill() method did not yet exist  These results are made possible by late-binding

Programming With Java ICS The final Modifier  A method marked final indicates that it cannot be overridden with a new definition in a derived class  If final, the compiler can use early binding with the method public final void someMethod() {... }  A class marked final indicates that it cannot be used as a base class from which to derive any other classes

Programming With Java ICS Upcasting and Downcasting  Upcasting is when an object of a derived class is assigned to a variable of a base class (or any ancestor class): Example: class Shape { int xpos, ypos ; public Shape(int x, int y){ xpos = x ; ypos = y ; } public void Draw() { System.out.println("Draw method called of class Shape") ; } }

Programming With Java ICS Upcasting and Downcasting class Circle extends Shape { int r ; public Circle(int x1, int y1, int r1){ super(x1, y1) ; r = r1 ; } public void Draw() { System.out.println("Draw method called of class Circle") ; } class UpcastingDemo { public static void main (String [] args) { Shape s = new Circle(10, 20, 4) ; s.Draw() ; } Output: Draw method called of class Circle

Programming With Java ICS Upcasting and Downcasting  When we wrote Shape S = new Circle(10, 20, 4), we have cast Circle to the type Shape.  This is possible because Circle has been derived from Shape  From Circle, we are moving up to the object hierarchy to the type Shape, so we are casting our object “upwards” to its parent type.

Programming With Java ICS Upcasting and Downcasting  Downcasting is when a type cast is performed from a base class to a derived class (or from any ancestor class to any descendent class). Example: class Shape { int xpos, ypos ; public Shape(int x, int y){ xpos = x ; ypos = y ; } public void Draw() { System.out.println("Draw method called of class Shape") ; }

Programming With Java ICS Upcasting and Downcasting class Circle extends Shape { int r ; public Circle(int x1, int y1, int r1){ super(x1, y1) ; r = r1 ; } public void Draw() { System.out.println("Draw method called of class Circle") ; } public void Surface() { System.out.println("The surface of the circle is " +((Math.PI)*r*r)); }

Programming With Java ICS Upcasting and Downcasting class DowncastingDemo { public static void main (String [] args) { Shape s = new Circle(10, 20, 4) ; ((Circle) s).Surface() ; } Output: The surface of the circle is 50.26

Programming With Java ICS Upcasting and Downcasting  When we wrote Shape s = new Circle(10, 20, 4) we have cast Circle to the type shape.  In that case, we are only able to use methods found in Shape, that is, Circle has inherited all the properties and methods of Shape.  If we want to call Surface() method, we need to down-cast our type to Circle. In this case, we will move down the object hierarchy from Shape to Circle :  ((Circle) s).Surface() ;

Programming With Java ICS Downcasting  It is the responsibility of the programmer to use downcasting only in situations where it makes sense  The compiler does not check to see if downcasting is a reasonable thing to do  Using downcasting in a situation that does not make sense usually results in a run-time error.