Polymorphism. Agenda

Similar documents
Inheritance and Polymorphism

Inheritance -- Introduction

Chapter 6 Reflection

ECE 122. Engineering Problem Solving with Java

11/19/2014. Inheritance. Chapter 7: Inheritance. Inheritance. Inheritance. Java Software Solutions for AP* Computer Science A 2nd Edition

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

Polymorphism. Polymorphism is an object-oriented concept that allows us to create versatile software designs

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Programming in C# Inheritance and Polymorphism

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

ECE 122. Engineering Problem Solving with Java

Java Object Oriented Design. CSC207 Fall 2014

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

CS-202 Introduction to Object Oriented Programming

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

What is Inheritance?

Object Oriented Programming. Java-Lecture 11 Polymorphism

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

CS 251 Intermediate Programming Inheritance

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

First IS-A Relationship: Inheritance

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

CS111: PROGRAMMING LANGUAGE II

Inheritance and Polymorphism

Example: Count of Points

C++ Important Questions with Answers

More Relationships Between Classes

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Chapter 5 Object-Oriented Programming

OVERRIDING. 7/11/2015 Budditha Hettige 82

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Inheritance, Polymorphism, and Interfaces

Binghamton University. CS-140 Fall Dynamic Types

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exercise: Singleton 1

CS 112 Introduction to Programming

Admin. q Admin and recap q Class inheritance

Inheritance and Polymorphism

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Inheritance and object compatibility

8.1 Inheritance. 8.1 Class Diagram for Words. 8.1 Words.java. 8.1 Book.java 1/24/14

Java Fundamentals (II)

More On inheritance. What you can do in subclass regarding methods:

Polymorphism and Interfaces. CGS 3416 Spring 2018

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Starting Out with Java: From Control Structures Through Objects Sixth Edition

ECE 122. Engineering Problem Solving with Java

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods

CMSC202 Computer Science II for Majors

Computer Science II (20073) Week 1: Review and Inheritance

CSCE3193: Programming Paradigms

Lecture 4: Extending Classes. Concept

Instance Members and Static Members

type conversion polymorphism (intro only) Class class

Example: Count of Points

Rules and syntax for inheritance. The boring stuff

Arrays Classes & Methods, Inheritance

INHERITANCE. Spring 2019

&KDSWHU(QKDQFLQJ&ODVVHV

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Polymorphism. Arizona State University 1

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

Implements vs. Extends When Defining a Class

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

CIS 190: C/C++ Programming. Lecture 11 Polymorphism

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Chapter 10: Inheritance

CMSC 132: Object-Oriented Programming II. Interface

CMSC 202. Generics II

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Inheritance and Polymorphism

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Chapter 10 Classes Continued. Fundamentals of Java

Inheritance (Outsource: )

Data Structures (list, dictionary, tuples, sets, strings)

Inheritance Motivation

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Chapter 11: Inheritance

8. Polymorphism and Inheritance

Inheritance (an intuitive description)

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Chapter 5. Inheritance

Object-Oriented Concepts

Transcription:

Polymorphism Lecture 11 Object-Oriented Programming Agenda Classes and Interfaces The Object Class Object References Primitive Assignment Reference Assignment Relationship Between Objects and Object References References and Inheritance Single vs. Multiple Inheritance Polymorphism Key points about Polymorphism Polymorphism via Interfaces 1

Classes and Interfaces Interface Models a role; defines a set of responsibilities Factors out common capabilities of dissimilar objects Declares, but does not define methods A class can implement multiple interfaces Class Models an object with properties and capabilities Factors out common properties and capabilities of similar objects Declares methods and may define some or all of them A class can extend only one superclass The Object Class A class called Object is defined in the java.lang package of the Java standard class library All classes are derived from the Object class If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class Therefore, the Object class is the ultimate root of all class hierarchies 2

The Object Class The Object class contains a few useful methods, which are inherited by all classes For example, the tostring method is defined in the Object class Every time we have defined tostring, we have actually been overriding an existing definition The tostring method in the Object class is defined to return a string that contains the name of the object s class together along with some other information The Object Class All objects are guaranteed to have a tostring method via inheritance Thus the println method can call tostring for any object that is passed to it 3

The Object Class The equals method of the Object class returns true if two references are aliases We can override equals in any class to define equality in some more appropriate way The String class defines the equals method to return true if two String objects contain the same characters Therefore the String class has overridden the equals method inherited from Object in favor of its own version Object References All interaction with an object occurs through object reference variables An object reference variable holds the reference (address, the location) of an object ChessPiece bishop1 = new ChessPiece(); bishop1 4

Primitive Assignment The act of assignment takes a copy of a value and stores it in a variable For primitive types: num1 5 Before num2 12 num2 = num1; num1 5 After num2 5 Reference Assignment For object references, the reference is copied: Before bishop2 = bishop1; bishop1 bishop2 After bishop1 bishop2 5

Relationship Between Objects and Object References Two or more references can refer to the same object; these references are called aliases of each other One object (and its data) can be accessed using different references References and Inheritance An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance For example, if the Holiday class is used to derive a child class called Eid, then a Holiday reference could actually be used to point to a Eid object Holiday Eid Holiday day; day = new Holiday(); day = new Eid(); 6

References and Inheritance Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment Holiday day = new Eid(); Assigning an ancestor object to a reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast Eid c1 = new Eid(); Holiday day = c1; Eid c2 = (Eid) day; The widening conversion is the most useful for implementing polymorphism References and Inheritance An object reference variable can refer to any object instantiated from its own class, or any class derived from it by inheritance For example, Holiday day; Holiday Eid day = new Holiday(); day = new Eid(); The assignment of an object of a derived class to a reference variable of the base class can be considered as a widening conversion 7

References and Inheritance Through a given type of reference variable, we can invoke only the methods defined in that type Holiday day; day = new Eid(); Can we do the following statements: day.celebrate(); day.gotoprayers(); class Holiday { public void celebrate() { class Eid extends Holiday { public void celebrate() { public void gotoprayers() { References and Inheritance We can promote an object back to its original type through an explicit narrowing cast: Holiday day = new Eid(); day.celebrate(); Eid e = (Eid) day; e.gotoprayers(); Question: which celebrate() will be invoked by the line: day.celebrate(); 8

What is Polymorphism? A polymorphic reference can refer to different types of objects at different times In java every reference can be polymorphic except of references to base types and final classes. It is the type of the object being referenced, not the reference type, that determines which method is invoked Polymorphic references are therefore resolved at run-time, not during compilation; this is called dynamic binding Careful use of polymorphic references can lead to elegant, robust software designs Polymorphism Polymorphism: A polymorphic reference v is declared as class C, but unless C is final or base type, v can refer to an object of class C or to an object of any class derived from C. A method call v.<method_name>(<args>) invokes a method of the class of an object referred to by v (not necessarily C): Ex1: Holiday day = new Eid(); day.celebrate(); Ex2: void process(holiday day) { day.celebrate(); Eid day =...; process(day) A very common usage of polymorphism: If classes C1, C2,..., Cn are all derived from C, define an array A of elements of C. The entries A[i] can then refer to objects of classes C1,..., Cn. 9

Single vs. Multiple Inheritance Some object-oriented languages allow multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents The price: collisions, such as the same variable name, same method name in two parents, have to be resolved Java decision: single inheritance, meaning that a derived class can have only one parent class Polymorphism Car SportsCar Van SUV SportsCar, Van, and SUV are all subclasses of the Car class Car has an abstract move() method that each of its subclasses define however, each of its subclasses defines this method differently 10

Polymorphism What happens when we: tell SportsCar to move()? (moves fast) tell Van to move()? (moves at a moderate speed) tell SUV to move()? (sometimes moves, sometimes just stops! Polymorphism is a fancy word for multiple forms, e.g., multiple forms of response to the same message Key points about Polymorphism A subclass inherits methods from its superclass; it can respond to all the same messages We can refer to an instance of a subclass as if it were an instance of its superclass relaxes strict type matching // Declaration: Car is the declared type of mycar Car mycar; // Instantiation: Van is the actual type of mycar mycar = new Van(); 11

Key points about Polymorphism Object will respond according to implementation defined in subclass! Assignment is NOT creating an instance of Car, which can only be done by new. It is a Car, but not an instance of Car! mycar.move(); // mycar will move like a Van, // though we refer to it as a Car! Can only call methods of the declared type! Thus can only call Car methods on mycar can t take advantage of any of the methods of the actual type Code Example /** * A simple example of Polymorphism doesn t show the full power... */ public class RaceTrack { private Car _car1, _car2, _car3; // note they're all declared as Cars public RaceTrack() { _car1 = new SportsCar(); _car2 = new Van(); _car3 = new SUV(); // but actual types are subtypes of Car 12

Code Example (Cont d) public void startrace() { // tell Car instances to move _car1.move(); _car2.move(); _car3.move(); /** Note: startrace coded polymorphically in terms of declared type Car, but methods will be called on instances of actual subtypes */ // end of class RaceTrack Class Knowledge When sending a message to an instance, we do not need to know its exact class... as long as it extends some superclass, we can send it any message we could send to the superclass but the message may be handled differently by the subclass than it would be by the superclass Classic example: shapes (similar to simple RaceTrack example) each shape subclass knows how to draw itself, but all do it differently simply say _shape.draw() 13

Another Code Example public class ShapeApp extends wheels.users.frame { private Shape _shape1,_shape2; public ShapeApp() { super(); _shape1 = new Triangle(); _shape2 = new Square(); public void drawshapes() { _shape1.draw(); _shape2.draw(); public static void main(string[] argv) { ShapeApp app = new ShapeApp(); Polymorphism via Interfaces Define a polymorphism reference through interface declare a reference variable of an interface type Doable obj; the obj reference can be used to point to any object of any class that implements the Doable interface the version of dothis depends on the type of object that obj is referring to: obj.dothis(); 14

More Examples Speaker guest; guest = new Philosopher(); guest.speak(); guest = Dog(); guest.speak(); Speaker special; special = new Philosopher(); // compiler error special.pontificate(); Speaker special; special = new Philosopher(); ((Philosopher)special).pontificate(); public interface Speaker { public void speak(); class Philosopher extends Human implements Speaker { // public void speak() { public void pontificate() { class Dog extends Animal implements Speaker { // public void speak() { Design Problem You are designing a program to sort a list of double values. However, you cannot use a predetermined sorting algorithm. Your choice of sorting algorithm must be made at runtime. What will you do to solve this problem? 15

Interface and Polymorphism Example public interface SortInterface { public void sort(double[] list); public class QuickSort implements SortInterface { public void sort(double[] a) { // quick sort code here public class BubbleSort implements SortInterface { public void sort(double[] list) { // bubble sort code here public class SortingContext { private SortInterface sorter = null; public void sortdouble(double[] list) { sorter.sort(list); public SortInterface getsorter() { return sorter; public void setsorter(sortinterface sorter) { this.sorter = sorter; public class SortingClient { public static void main(string[] args) { double[] list = {1,2.4,7.9,3.2,1.2,0.2,10.2,22.5,19.6; SortingContext context = new SortingContext(); context.setsorter(new BubbleSort()); context.sortdouble(list); for(int i =0; i< list.length; i++) { System.out.println(list[i]); Strategy Pattern The code we just saw is called a Strategy Pattern. It uses the polymorphic behavior through interfaces. 16

Readings Book Name: Head First JAVA Author Name: Kathy Sierra & Bert Bates Content: Chapter # 7 & 8 17