Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

Similar documents
Advanced Placement Computer Science. Inheritance and Polymorphism

Rules and syntax for inheritance. The boring stuff

Topic 10. Abstract Classes. I prefer Agassiz in the abstract, rather than in the concrete.

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Inheritance. Transitivity

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

ITI Introduction to Computing II

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

COMP 250. Lecture 32. polymorphism. Nov. 25, 2016

ITI Introduction to Computing II

Introduction to Programming Using Java (98-388)

AP CS Unit 6: Inheritance Notes

Inheritance. A key OOP concept

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

Making New instances of Classes

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

Inheritance and Polymorphism

CLASS DESIGN. Objectives MODULE 4

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Java Magistère BFA

CS-202 Introduction to Object Oriented Programming

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

Practice for Chapter 11

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Chapter 15: Object Oriented Programming

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

TeenCoder : Java Programming (ISBN )

Super-Classes and sub-classes

More about inheritance

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

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

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

CompuScholar, Inc. 9th - 12th grades

CISC370: Inheritance

CH. 2 OBJECT-ORIENTED PROGRAMMING

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

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

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

A Java Execution Simulator

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

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

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

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Inheritance (Part 5) Odds and ends

What is Inheritance?

Objects and Iterators

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

The class Object. Lecture CS1122 Summer 2008

Introduction to Inheritance

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

INHERITANCE. Spring 2019

CS 200 More Classes Jim Williams, PhD

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Inheritance and Polymorphism

Generics method and class definitions which involve type parameters.

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

Inheritance and Polymorphism. CS180 Fall 2007

Java Fundamentals (II)

Inheritance. Exploring Polymorphism. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Topic 3 Encapsulation - Implementing Classes

6.005 Elements of Software Construction Fall 2008

CS Programming I: Inheritance

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

CS 251 Intermediate Programming Inheritance

CS 11 java track: lecture 3

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Programming II (CS300)

Last class. -More on polymorphism -super -Introduction to interfaces

Lecture 2: Java & Javadoc

Java Review: Objects

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

Static and Dynamic Behavior לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

CS Week 13. Jim Williams, PhD

Polymorphism. return a.doublevalue() + b.doublevalue();

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Inheritance, Polymorphism, and Interfaces

Java Programming Training for Experienced Programmers (5 Days)

Java Object Oriented Design. CSC207 Fall 2014

Language Features. 1. The primitive types int, double, and boolean are part of the AP

COMP 401 INITIALIZATION AND INHERITANCE. Instructor: Prasun Dewan

OVERRIDING. 7/11/2015 Budditha Hettige 82

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

Binghamton University. CS-140 Fall Dynamic Types

Logistics. Final Exam on Friday at 3pm in CHEM 102

Multiple Inheritance, Abstract Classes, Interfaces

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

Binghamton University. CS-140 Fall Chapter 9. Inheritance

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Lecture 10. Overriding & Casting About

Abstract Classes and Interfaces

CS 211: Inheritance. Chris Kauffman. Week 5-2

Inheritance -- Introduction

Class, Variable, Constructor, Object, Method Questions

Transcription:

Topic 5 Polymorphism " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code. 1

Polymorphism Another feature of OOP literally having many forms object variables in Java are polymorphic object variables can refer to objects or their declared type AND any objects that are descendants of the declared type Property p = new Property(); p = new Railroad(); // legal! p = new Utility(); //legal! p = new Street(); Object obj1; // = what? CS314 Polymorphism 2

Data Type object variables have: a declared type. Also called the static type. a dynamic type. What is the actual type of the pointee at run time or when a particular statement is executed. Method calls are syntactically legal if the method is in the declared type or any ancestor of the declared type The actual method that is executed at runtime is based on the dynamic type dynamic dispatch CS314 Polymorphism 3

Clicker Question 1 Consider the following class declarations: public class BoardSpace public class Property extends BoardSpace public class Street extends Property public class Railroad extends Property Which of the following statements would cause a syntax error? (Assume all classes have a zero argument constructor.) A. Object obj = new Railroad(); B. Street s = new BoardSpace(); C. BoardSpace b = new Street(); D. Railroad r = new Street(); E. More than one of these CS314 Polymorphism 4

Method LookUp To determine if a method is legal the compiler looks in the class based on the declared type if it finds it great, if not go to the super class and look there continue until the method is found, or the Object class is reached and the method was never found. (Compile error) To determine which method is actually executed the run time system: starts with the actual run time class of the object that is calling the method search the class for that method if found, execute it, otherwise go to the super class and keep looking repeat until a version is found Is it possible the runtime system won t find a method? CS314 Polymorphism 5

Clicker Question 2 What is output by the code to the right when run? A.!!live B.!eggegg C.!egglive D.!!! E. Something else public class Animal{ public String bt(){ return "!"; } } public class Mammal extends Animal{ } public String bt(){ return "live"; } public class Platypus extends Mammal{ public String bt(){ return "egg";} } Animal a1 = new Animal(); Animal a2 = new Platypus(); Mammal m1 = new Platypus(); System.out.print( a1.bt() ); System.out.print( a2.bt() ); System.out.print( m1.bt() ); CS314 Polymorphism 6

Why Bother? Inheritance allows programs to model relationships in the real world if the program follows the model it may be easier to write Inheritance allows code reuse complete programs faster (especially large programs) Polymorphism allows code reuse in another way Inheritance and polymorphism allow programmers to create generic algorithms CS314 Polymorphism 7

Genericity One of the goals of OOP is the support of code reuse to allow more efficient program development If a algorithm is essentially the same, but the code would vary based on the data type genericity allows only a single version of that code to exist in Java, there are 2 ways of doing this 1. polymorphism and the inheritance requirement 2. generics CS314 Polymorphism 8

A Generic List Class CS314 Polymorphism 9

Back to IntList We may find IntList useful, but what if we want a List of Strings? Rectangles? Lists? What if I am not sure? Are the List algorithms different if I am storing Strings instead of ints? How can we make a generic List class? CS314 Polymorphism 10

Generic List Class required changes How does tostring have to change? why?!?! A good example of why keyword this is necessary from tostring What can a List hold now? How many List classes do I need? CS314 Polymorphism 11

Writing an equals Method How to check if two objects are equal? if(obja == obja) // does this work? Why not this public boolean equals(list other) Because public void foo(list a, Object b) if( a.equals(b) ) System.out.println( same ) what if b is really a List? CS314 Polymorphism 12

equals method read the javadoc carefully! Must handle null Parameter must be Object otherwise overloading instead of overriding causes must handle cases when parameter is not same data type as calling object instanceof or getclass() don't rely on tostring and String's equals CS314 Polymorphism 13

the createaset example public Object[] createaset(object[] items) { /* pre: items!= null, no elements of items = null post: return an array of Objects that represents a set of the elements in items. (all duplicates removed) */ {5, 1, 2, 3, 2, 3, 1, 5} -> {5, 1, 2, 3} CS314 Polymorphism 14

createaset examples String[] slist = {"Texas", "texas", "Texas", "Texas", "UT", "texas"}; Object[] sset = createaset(slist); for(int i = 0; i < sset.length; i++) System.out.println( sset[i] ); Object[] list = {"Hi", 1, 4, 3.3, true, new ArrayList(), "Hi", 3.3, 4}; Object[] set = createaset(list); for(int i = 0; i < set.length; i++) System.out.println( set[i] ); CS314 Polymorphism 15