1 Object-Oriented Programming: Polymorphism 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy 10.2.1 Invoking Superclass Methods.

Slides:



Advertisements
Similar presentations
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Relationships Among.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 27 - Java Object-Oriented Programming Outline.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Outline 1 Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü.
1 Evan Korth New York University abstract classes and casting Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
 2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 8 – Sections covered
1 Lecture Note 9_Polymorphism Outline Relationships Among Objects in an Inheritance Hierarchy Invoking Base-Class Functions from Derived-Class object Virtual.
C++ Polymorphism Systems Programming. Systems Programming: Polymorphism 2   Polymorphism Examples   Relationships Among Objects in an Inheritance.
Object-Oriented Programming: Polymorphism
Object Oriented Programming using Java - Polymorphism
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
Object Oriented Concepts
CISC6795: Spring Object-Oriented Programming: Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Lecture 9 Polymorphism Richard Gesick.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Object-Oriented Programming: Polymorphism Zhen Jiang West Chester University
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Mark Fontenot CSE Honors Principles of Computer Science I Note Set 14.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
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.,
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Inheritance & Polymorphism1. 2 Introduction Besides composition, another form of reuse is inheritance. With inheritance, an object can inherit behavior.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Superclasses and Subclasses.
Java Programming Dr. Randy Kaplan. Abstract Classes and Methods.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance and Design CSIS 3701: Advanced Object Oriented Programming.
O O P Polymorphism Object Oriented Programming Prepared & Presented by: dr.Ismail Farahat Chapter 4.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
1 Lecture 8 Chapter 10 - Object-Oriented Programming: Polymorphism Outline Introduction Relationships Among Objects in an Inheritance Hierarchy Invoking.
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
© 2007 Lawrenceville Press Slide 1 Chapter 9 Inheritance  One class is an extension of another.  Allows a class to define a specialized type of an existing.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance ndex.html ndex.htmland “Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Object-Oriented Programming: Polymorphism Chapter 10.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Base Classes and Derived.
 2002 Prentice Hall. All rights reserved. Page 1 Inheritance: Object-Oriented Programming Outline 9.1 Introduction 9.2 Superclasses and Subclasses 9.3.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism.
 2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
C++ How to Program, 7/e. © by Pearson Education, Inc. All Rights Reserved.2.
C++ How to Program, 7/e.  There are cases in which it’s useful to define classes from which you never intend to instantiate any objects.  Such classes.
Learning Objectives Relationships Among Objects in an Inheritance Hierarchy. Invoking Base-class Functions from Derived Class Objects. Aiming Derived-Class.
Sixth Lecture ArrayList Abstract Class and Interface
Sections Inheritance and Abstract Classes
Inheritance and Polymorphism
Object-Oriented Programming: Inheritance
abstract classes and casting objects
Object-Oriented Programming: Polymorphism
Lecture 23 Polymorphism Richard Gesick.
Object-Oriented Programming: Polymorphism
Week 6 Object-Oriented Programming (2): Polymorphism
Polymorphism and Type Casting
Object-Oriented Programming: Polymorphism
Presentation transcript:

1 Object-Oriented Programming: Polymorphism 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy Invoking Superclass Methods from Subclass Objects Using Superclass References with Subclass-Type Variables Subclass Method Calls via Superclass-Type Variables 10.3 Polymorphism Examples 10.4 Abstract Classes and Methods 10.5 Case Study: Inheriting Interface and Implementation 10.6 final Methods and Classes 10.7 Case Study: Payroll System Using Polymorphism 10.8 Case Study: Creating and Using Interfaces 10.9 Type-Wrapper Classes for Primitive Types

Introduction Polymorphism –“Program in the general” –Treat objects in same class hierarchy as if all superclass –Abstract class Common functionality –Makes programs extensible New classes added easily, can still be processed In our examples –Use abstract superclass Shape Defines common interface (functionality) Point, Circle and Cylinder inherit from Shape –Class Employee for a natural example

Relationships Among Objects in an Inheritance Hierarchy Previously –Circle inherited from Point –Manipulated Point and Circle objects using references to invoke methods This section –Invoking superclass methods from subclass objects –Using superclass references with subclass-type variables –Subclass method calls via superclass-type variables Key concept –subclass object can be treated as superclass object “is-a” relationship superclass is not a subclass object

Invoking Superclass Methods from Subclass Objects Store references to superclass and subclass objects –Assign a superclass reference to superclass-type variable –Assign a subclass reference to a subclass-type variable Both straightforward –Assign a subclass reference to a superclass variable “is a” relationship..\..\week9\relationships_1

Using Superclass References with Subclass-Type Variables Previous example –Assigned subclass reference to superclass-type variable Circle “is a” Point Assign superclass reference to subclass-type variable –Compiler error No “is a” relationship Point is not a Circle Circle has data/methods that Point does not –setRadius (declared in Circle ) not declared in Point –Cast superclass references to subclass references Called downcasting Invoke subclass functionality

6 1 // HierarchyRelationshipTest2.java 2 // Attempt to assign a superclass reference to a subclass-type variable. 3 4 public class HierarchyRelationshipTest2 { 5 6 public static void main( String[] args ) 7 { 8 Point3 point = new Point3( 30, 50 ); 9 Circle4 circle; // subclass-type variable // assign superclass reference to subclass-type variable 12 circle = point; // Error: a Point3 is not a Circle4 13 } } // end class HierarchyRelationshipTest2 HierarchyRelationshipTest2.java:12: incompatible types found : Point3 required: Circle4 circle = point; // Error: a Point3 is not a Circle4 ^ 1 error Assigning superclass reference to subclass-type variable causes compiler error

Subclass Method Calls via Superclass-Type variables Call a subclass method with superclass reference –Compiler error Subclass methods are not superclass methods

8 1 // HierarchyRelationshipTest3.java 2 // Attempting to invoke subclass-only member methods through 3 // a superclass reference. 4 5 public class HierarchyRelationshipTest3 { 6 7 public static void main( String[] args ) 8 { 9 Point3 point; 10 Circle4 circle = new Circle4( 120, 89, 2.7 ); point = circle; // aim superclass reference at subclass object // invoke superclass (Point3) methods on subclass 15 // (Circle4) object through superclass reference 16 int x = point.getX(); 17 int y = point.getY(); 18 point.setX( 10 ); 19 point.setY( 20 ); 20 point.toString(); 21

9 22 // attempt to invoke subclass-only (Circle4) methods on 23 // subclass object through superclass (Point3) reference 24 double radius = point.getRadius(); 25 point.setRadius( ); 26 double diameter = point.getDiameter(); 27 double circumference = point.getCircumference(); 28 double area = point.getArea(); } // end main } // end class HierarchyRelationshipTest3 Attempt to invoke subclass- only ( Circle4 ) methods on subclass object through superclass ( Point3 ) reference.

10 HierarchyRelationshipTest3.java:24: cannot resolve symbol symbol : method getRadius () location: class Point3 double radius = point.getRadius(); ^ HierarchyRelationshipTest3.java:25: cannot resolve symbol symbol : method setRadius (double) location: class Point3 point.setRadius( ); ^ HierarchyRelationshipTest3.java:26: cannot resolve symbol symbol : method getDiameter () location: class Point3 double diameter = point.getDiameter(); ^ HierarchyRelationshipTest3.java:27: cannot resolve symbol symbol : method getCircumference () location: class Point3 double circumference = point.getCircumference(); ^ HierarchyRelationshipTest3.java:28: cannot resolve symbol symbol : method getArea () location: class Point3 double area = point.getArea(); ^ 5 errors

Polymorphism Examples Examples –Suppose Rectangle derives from Quadrilateral Rectangle more specific than Quadrilateral Any operation on Quadrilateral can be done on Rectangle (i.e., perimeter, area) Suppose designing video game –Superclass SpaceObject Subclasses Martian, SpaceShip, LaserBeam Contains method draw –To refresh screen Send draw message to each object Same message has “many forms” of results

Polymorphism Examples Video game example, continued –Easy to add class Mercurian Extends SpaceObject Provides its own implementation of draw –Programmer does not need to change code Calls draw regardless of object’s type Mercurian objects “plug right in”

Abstract Classes and Methods Abstract classes –Are superclasses (called abstract superclasses) –Cannot be instantiated –Incomplete subclasses fill in "missing pieces" Concrete classes –Can be instantiated –Implement every method they declare –Provide specifics

Abstract Classes and Methods (Cont.) Abstract classes not required, but reduce client code dependencies To make a class abstract –Declare with keyword abstract –Contain one or more abstract methods public abstract void draw(); –Abstract methods No implementation, must be overridden

Abstract Classes and Methods (Cont.) Application example –Abstract class Shape Declares draw as abstract method –Circle, Triangle, Rectangle extends Shape Each must implement draw –Each object can draw itself Iterators –Array, ArrayList (Chapter 22) –Walk through list elements –Used in polymorphic programming to traverse a collection

Case Study: Inheriting Interface and Implementation Make abstract superclass Shape –Abstract method (must be implemented) getName, print Default implementation does not make sense –Methods may be overridden getArea, getVolume –Default implementations return 0.0 If not overridden, uses superclass default implementation –Subclasses Point, Circle, Cylinder

Case Study: Inheriting Interface and Implementation Circle Cylinder Point Shape Fig Shape hierarchy class diagram.

Case Study: Inheriting Interface and Implementation 0.0 = "Point"[x,y] pr2pr2 0.0"Circle" center=[x,y]; radius=r 2pr 2 +2prhpr2hpr2h "Cylinder" center=[x,y]; radius=r; height=h getAreaprintgetNamegetVolume Shape Point Circle Cylinder Polimorphic interface for the Shape hierarchy classes...\..\week9\case-study1

final Methods and Classes final methods –Cannot be overridden –private methods are implicitly final –static methods are implicitly final final classes –Cannot be superclasses –Methods in final classes are implicitly final –e.g., class String

Case Study: Payroll System Using Polymorphism Create a payroll program –Use abstract methods and polymorphism Problem statement –4 types of employees, paid weekly Salaried (fixed salary, no matter the hours) Hourly (overtime [>40 hours] pays time and a half) Commission (paid percentage of sales) Base-plus-commission (base salary + percentage of sales) –Boss wants to raise pay by 10%

Case Study: Payroll System Using Polymorphism Superclass Employee –Abstract method earnings (returns pay) abstract because need to know employee type Cannot calculate for generic employee –Other classes extend Employee Employee SalariedEmployeeHourlyEmployeeCommissionEmployee BasePlusCommissionEmployee..\..\week9\case-study2

Case Study: Creating and Using Interfaces Use interface Shape –Replace abstract class Shape Interface –Declaration begins with interface keyword –Classes implement an interface (and its methods) –Contains public abstract methods Classes (that implement the interface) must implement these methods

23 1 // Shape.java 2 // Shape interface declaration. 3 4 public interface Shape { 5 public double getArea(); // calculate area 6 public double getVolume(); // calculate volume 7 public String getName(); // return shape name 8 9 } // end interface Shape Classes that implement Shape must implement these methods..\..\week9\case-study3

Case Study: Creating and Using Interfaces (Cont.) Implementing Multiple Interface –Provide common-separated list of interface names after keyword implements Declaring Constants with Interfaces –public interface Constants { public static final int ONE = 1; public static final int TWO = 2; public static final int THREE = 3; }..\..\week9\case-study4

Type-Wrapper Classes for Primitive Types Type-wrapper class –Each primitive type has one Character, Byte, Integer, Boolean, etc. –Enable to represent primitive as Object Primitive types can be processed polymorphically –Declared as final –Many methods are declared static Check API.