Lectures 11-1, Polymorphism. Introduction to Computer Science, Shimon Schocken slide 1

Similar documents
Advertising packages 2018

WORKING GROUP HAZARDOUS WASTE Work program

The provision of same-day care in general practice: an observational study

Equity in Athletics 2017 Institution Information

NAVAL MINES INTRODUCTION: EOD CONSIDERATIONS CONTACT MINES: SAFETY FOR OFFICIAL USE ONLY FOR OFFICIAL USE ONLY

H0006 Case Management $ Minute Increment 1-28 Units per month

ASSOCIATION OF SENIOR LIVING INDIA CODE OF PRACTICE

SYLLABUS TAXATION 2 ECAU EVEN SEMESTER 2016/2017

Lectures 9-1, 9-2. Collections. Introduction to Computer Science, Shimon Schocken slide 1

Return of Private Foundation

A HISTORY OF RADIO A RADIO INTERVIEW. Teacher s notes 1 ARTS AND MEDIA

AETC Philosophy Future Requirements Combat Systems Officer Training Remotely Piloted Aircraft Training Future of Pilot Training

Undergraduate Student Workbook

Table of Contents. What is Branding and Why is it Important? The Shield of the College Selecting the Correct File Format...

Maneuver Center of Excellence (MCoE) Libraries HQ Donovan Research Library Armor Research Library Fort Benning, Georgia

HEALTH SERVICE COSTS IN EUROPE: COST AND REIMBURSEMENT OF PRIMARY HIP REPLACEMENT IN NINE COUNTRIES

Goals of System Modeling:

MEDICAL SURVEILLANCE MONTHLY REPORT

Multi HLR Architecture for Improving Location Management in PCS Network

ALABAMA ASSOCIATION of EMERGENCY MANAGERS

abstract SUPPLEMENT ARTICLE

2018 SALES & EXHIBITOR GUIDE

Obtaining peripheral vascular access in

Introduction. Methods

EXCAVATION & FILL PROCEDURE 1

SEMI-ELLIPTICAL SURFACE FLAW EC INTERACTION AND INVERSION: THEORY. B. A. Auld and s. Jefferies

As organizations strive to improve

Return of Private Foundation

Return of Private Foundation

Next Gen Training. Why is Next Gen So Important? Step-by-Step Vitals Entry Scenarios and Mock Work-ups

What is the best way for providers to ask patients about antiretroviral adherence?

Digital Public Services. Digital Economy and Society Index Report 2018 Digital Public Services

Interfaith Council Social Action Committee of Sun City Center, Florida Instructions for Grant Application Form

MEDICAL SURVEILLANCE MONTHLY REPORT

Application for Funding

COUNTY OF LOS ANGELES DEPARTMENT OF AUDITOR.CONTROLLER

The weather was great, the

OPEN DOORS FINANCIAL ASSISTANCE. oceancommunityymca.org. The Y: So Much More.

Bringing Climate Opportunities to Entrepreneurs: Lessons Learned from the Caribbean Climate Innovation Center

Scope. Berkshire Medical Center had. MAKO Arthroplasty on Display for Community at BMC Latest Joint Replacement Technology for Hip & Knee

OPD 201A - Unit Administration

Strategic Plan for the Internationalization of UDEM

TRECA Tri-Rivers Educational Computer Association 2222 Marion-Mt. Gilead Road Marion, OH Parent Assist Module Parents

Free clinics are often overlooked as a part of the US health

I am directed to refer to the captioned subject and to forward herewith a copy of

Kong. meeting. was invited to. 1 st Section activities: Details Date 21 & 22 January R10 EXCOM. in Hong Kong. meeting in.

Table of Contents. Letter from the Sheriff 3-4 Comparative Summary 5-7 Organizational Charts 8-12 Call History Countywide 13-15, 69 Calls for Service

Operational Excellence: Lean

* WELCOME TO THE GCRC CENSUS * * SYSTEM *

Malaria surveillance, monitoring and evaluation manual

RECRUIT SUSTAINMENT PROGRAM SOLDIER TRAINING READINESS MODULES Leadership Overview 9 July 2012

III orks I, II, orks IV ater I ater II ater III ater IV ngth Mi terw terw stew stew stew stew nageme urse Le Course Name Code Water/Wastewater

Guarantor: William F. Page, PhD Contributors: Clare M. Mahan, PhD*; William F. Page, PhD ; Tim A. Bullman, MS*; Han K. Kang, DrPH*

American Farm Bureau Federation Young Farmers & Ranchers Excellence in Agriculture Award. Rules for 2019 AFBF Annual Convention Competition

CERNER MILLENNIUM Admission From Office

Bloom Period Management of Lygus bug in Alfalfa Seed

Care Fragmentation IOM 09/09/09

A new Youth Guarantee for Europe: Roadmap for Member States

Instructions and Background on Using the Telehealth ROI Estimator

Developmental Test & Evaluation OUSD(AT&L)/DDR&E

MARKET INSIGHT INDIANAPOLIS MULTIFAMILY REPORT FOURTH QUARTER 2017

ALIFORNIA CHAPTER NETLETTER

Your Guide to Success. Interface & User Experience Design

HEXBUG Nano V2 #THEYCANCLIMB Coloring Contest

July 1, 2017 EMERGENCY PROCEDURES FOR DEPARTMENT OF ALLIED HEALTH SCIENCES IN BONDURANT HALL

Reliv Master Affiliate what s next?

Resident Remediation

Elementary Seabee Discovery Game

l flilt! [ ililtiluru a

SPEECH BY THE MINISTER OF HEALTH: SOUTH AFRICA DR AARON MOTSOALEDI INTERNATIONAL SYMPOSIUM ON DESIGN AND HEALTH IN QATAR, DOHA

Arthropod. Fecal-oral. Exposure/exertion. Hepatitis Hepatitis B. Sexually transmitted. Page 24. MSMR Vol. 19 No. 4 April Lyme disease.

The For-Profitization of Affordable Housing Development and the de Blasio Plan

ADDENDUM #1 LRT SS SECURITY SERVICES

Prompt: Describe the effects of the new technology on warfare during WWI.

INTEGRA TED RURAL WA TEA SL/PPL Y AND SAN/TA TION PROJECT, KARNA TAKA, INDIA

Teamwork, Discipline, Accountability, Lethality, Mental Toughness, Respect. Vision and Priorities Enduring Intent Imperatives.

Rutgers University Into the Light Walk September 23, 2017

MARINE SAFETY MANAGEMENT SYSTEM

TABLE OF CONTENTS. How Does Fundraising Make a Difference?

Minnesota Farm Bureau Federation Young Farmers & Ranchers Excellence in Agriculture Award. Rules for 2018 MFBF Annual Convention Competition

OBJECT ORIENTED SYSTEM MODELLING

de structive capability different from other weapons. The overwhelming cities some hours or even days

Analysis of the Survey of the Working Group EU-Financing. 2004/2005: EU-Programmes, June 2005

August 2017 Su Mon Tues Wed Thu Fri Sat

CSE255 Introduction to Databases - Fall 2007 Semester Project Overview and Phase I

Innovation Case Study. Ros Graves Project Manager, Innovation Medilink East Midlands Ltd.

Quality of care for under-fives in first-level health facilities in one district of Bangladesh

How To Shortlist Top Job Candidates: A Checklist

How To Shortlist Top Job Candidates: A Checklist

Get Started with Health Cloud

i' ~t to CIJ~ ~lb ">9""

Table of Contents. Letter from the Sheriff 3-4 Comparative Summary 5-7 Organizational Charts 8-12 Call History Countywide 13-15, 69 Calls for Service

UC MERCED EXIT DISCOVERING YOUR JOURNEY TO SUCCESS NEXT EXIT

Questions to Ask About Military Child Care Waiting Lists and Costs

Purpose/Goal: This course introduces the purpose and use of Smart Chart as a means of legal documentation.

LONG-RANGE SURVEILLANCE RECONNAISSANCE

Western Cape: Research strategy and way forward. Tony Hawkridge Director: Health Impact Assessment Western Cape Government: Health

Gazette Post Office Box Court Street. Ville Platte, LA Ph: or Fax:

Rapportens tittel. Norway Rapport xx Rapport

CS Mandatory Access Control, part 2. Prof. Clarkson Spring 2016

Transcription:

Lectures 11-1, 11-2 Polmorphism Introduction to Computer Science, Shimon Schocken slide 1 Polmorphism Jv is dnmic lnguge : Run-time object tpes Virtul method invoction (k lte binding / dnmic binding ) Impliction: Polmorphism The behvior obtined b invoking method obj.m cn tke different m ccording to run-time tpe object obj Theree, objects belonging to different tpes cn respond to method cll sme nme, ech ccording to different tpe-specific implementtion The clling progrm does not hve to know object tpe in dvnce; The ect behvior is determined in run-time. Introduction to Computer Science, Shimon Schocken slide 2 Intorduction to Computer Science IDC Herzli Shimon Schocken

Wht re problems to which polmorphism is solution? Quite ten we hve to represent collection objects different tpes tht hve to hve similr but different behvior. Emples: Proll ppliction: Different Worker tpes: fied slr hourl-workers, volunteers, Common behvior: we hve to p ech Worker ccording to his/her sub-tpe Emploee Proll Slip Nme: John Smith P Period: Dec 1, 2009 Dec 31, 2009 Worker tpe: Hourl worker Hourl P: $15.00 Hours Worked: 31 Totl due: $465.00 Computer gme: Different Fighter tpes: boers, ninjs, shooters, Common behvior: ever Fighter hits in some sub-tpe specific w Pbrush ppliction: Different tpes: lines, rectngles, circles, Common behvior: ever figure drws itself in some sub-tpe specific w Introduction to Computer Science, Shimon Schocken slide 3 A polmorphic design pproch 1. Design bse clss, or n erfce 2. Implement ech sub-tpe s: A clss tht etends bse-clss, or A clss tht implements erfce 3. Represent common behvior s n bstrct method t bse-clss or t erfce level Emploee Proll Slip Nme: John Smith P Period: Dec 1, 2009 Dec 31, 2009 Worker tpe: Hourl worker Hourl P: $15.00 Hours Worked: 31 Totl due: $465.00 4. Hve ech sub-clss implement method in sub-tpe specific w 5. This design llows ou to invoke sme method on n object, knowing tht object will know how to hndle itself. This is essence polmorphism. Introduction to Computer Science, Shimon Schocken slide 4 Intorduction to Computer Science IDC Herzli Shimon Schocken

Emple: zoo erfce erfce Animl Animl sound sound ; ; clss Dog implements Animl sound "Wo"; clss Pig implements Animl sound "Oink"; clss Mouse implements Animl sound "Squek"; complin "Ouch!"; Cn store n subtpe Animl zoo is n rr objects tht implement Animl erfce. clss clss AnimlDemo AnimlDemo sttic sttic min([] min([] rgs) rgs) Animl[] Animl[] zoo zoo Animl[4]; Animl[4]; zoo[0] zoo[0] Pig; Pig; zoo[1] zoo[1] Pig; Pig; zoo[2] zoo[2] Mouse; Mouse; zoo[3] zoo[3] Dog; Dog; (Animl : zoo) Sstem.out.prln(.sound.sound); if ( instnce Mouse) Mouse m (Mouse) ; Polmorphic method invoction Sstem.out.prln(m.complin); Introduction to Computer Science, Shimon Schocken slide 5 Abstrct clss vs. erfce erfce erfce Animl Animl sound sound ; ; clss clss Dog Dog implements implements Animl Animl sound sound "Wo"; "Wo"; Could be replced with: bstrct bstrct clss clss Animl Animl bstrct bstrct sound sound ; ; clss clss Dog Dog etends etends Animl Animl sound sound "Wo"; "Wo"; Best prctice: Use bstrct clsses when ou wnt to declre dt nd implement some methods t bse-clss level Use erfces whenever possible sstems bsed on erfce inheritnce re fr more stble nd es to mnge thn sstems bsed on clss inheritnce. Introduction to Computer Science, Shimon Schocken slide 6 Intorduction to Computer Science IDC Herzli Shimon Schocken

Outline Polmorphism Emples polmorphic solutions: Fighting rm Proll Pbrush Revisiting erfces Introduction to Computer Science, Shimon Schocken slide 7 A fighting rm Introduction to Computer Science, Shimon Schocken slide 8 Intorduction to Computer Science IDC Herzli Shimon Schocken

Kung Fu Fighter erfce erfce Fighter Fighter hit hit ; ; clss clss KungFuFighter KungFuFighter implements implements Fighter Fighter hit hit Sstem.out.pr("trch! Sstem.out.pr("trch! "); "); Introduction to Computer Science, Shimon Schocken slide 9 Boer Fighter erfce erfce Fighter Fighter hit; hit; leftleftor or right-hnded right-hnded boer. boer. clss clss Boer Boer implements implements Fighter Fighter boolen boolen netpunchleft; netpunchleft; eir eir leftleftor or right-hnded right-hnded Boer Boer Boer Boer (boolen (boolen lefthnded) lefthnded) netpunchleft netpunchleft lefthnded; lefthnded; hit hit Sstem.out.pr(netPunchLeft Sstem.out.pr(netPunchLeft?? "left "left punch! punch! " " : : "right "right punch! punch! "); "); netpunchleft netpunchleft!netpunchleft;!netpunchleft; Introduction to Computer Science, Shimon Schocken slide 10 Intorduction to Computer Science IDC Herzli Shimon Schocken

A fighting rm import import jv.util.rndom; jv.util.rndom; clss clss FightingArm FightingArm sttic sttic min([] min([] rgs) rgs) Cretes nd popultes n rm 10 fighters Fighter[] soldiers Fighter[10]; ( i 0; i < soldiers.length; i) if (Mth.rndom > 0.5) soldiers[i] Boer(true); else soldiers[i] KungFuFighter; For ech fighter, prs his number nd genertes rndom series t most 4 hits ( i 0; i < soldiers.length; i) Sstem.out.pr("Soldier " i ": "); Terminolog some OO lnguges Method clls, e.g..m, re sometimes referred to s sending messge m to object Different objects respond to sme messge in different ws, depending on ir tpe. nhits 1 ( Rndom).netInt(3); ( k 0; k < nhits ; k) soldiers[i].hit; Sstem.out.prln; Polmorphic method invoction Introduction to Computer Science, Shimon Schocken slide 11 Outline Polmorphism Emples polmorphic solutions: Fighting rm Proll Pbrush Revisiting erfces Introduction to Computer Science, Shimon Schocken slide 12 Intorduction to Computer Science IDC Herzli Shimon Schocken

Proll ppliction Our compn emplos vrious tpes workers. We hve regulr emploees, who re pid monthl slr we hve hourl workers, who we p ccording to hours ctull worked, nd we hve volunteers, who don t get pid. We lso hve eecutives. The eecutives re emploees, mening tht get monthl slr. But, m lso get monthl bonus, becuse set proll polic. We need proll sstem tht, ech month, ps ech worker his or her due. Emploee Proll Slip Nme: John Smith P Period: Dec 1, 2009 Dec 31, 2009 Worker tpe: Hourl worker Hourl P: $15.00 Hours Worked: 31 Totl due: $465.00 Introduction to Computer Science, Shimon Schocken slide 13 Design considertions Identifing entities: Our compn emploees vrious tpes workers. We hve emploees, who re pid monthl slr we hve hourl workers, who we p ccording to hours ctull worked, nd we hve volunteers, who don t get pid. We lso hve eecutives. The eecutives re emploees, mening tht get monthl slr. But, m lso get monthl bonus, tht reflects ir chievements during month. Observtions: Emploee is- worker Hourl-worker is- worker Volunteer is- worker Eecutive is-n emploee Design decision: It mkes sense to put s much common dt nd functionlit in Worker clss, nd derive specific worker sub-clsses from it. Introduction to Computer Science, Shimon Schocken slide 14 Intorduction to Computer Science IDC Herzli Shimon Schocken

Proll clss digrm Worker (bstrct) - nme : to : p : double (bstrct) HourlWorker - hourlrte : double - hoursworked : ddhours ( morehours) : to : p : double Emploee - slr : double to : p : double Volunteer to : p : double Eecutive - bonus : double setbonus (double bonus) : to : p : double Introduction to Computer Science, Shimon Schocken slide 15 Proll clss digrm Worker (bstrct) - nme : to : p : double (bstrct) HourlWorker - hourlrte : double - hoursworked : ddhours ( morehours) : to : p : double Emploee - slr : double to : p : double Volunteer to : p : double Eecutive - bonus : double setbonus (double bonus) : to : p : double Introduction to Computer Science, Shimon Schocken slide 16 Intorduction to Computer Science IDC Herzli Shimon Schocken

Sub-clssing Worker: Volunteer bse-clss generic generic bstrct bstrct clss clss Worker Worker sub-clss volunteer volunteer clss clss Volunteer Volunteer etends etends Worker Worker dt: dt: nme; nme; dt dt comes comes here here worker worker Worker Worker ( ( nme) nme).nme.nme nme; nme; to to "Nme: "Nme: " " nme; nme; Ps Ps bstrct bstrct double double p p ; ; volunteer. volunteer. Volunteer Volunteer ( ( nme) nme) super super (nme); (nme); to to super.to super.to "\n" "\n" "Volunteer, "Volunteer, no no pment"; pment"; Volunteers Volunteers receive receive no no pment. pment. double double p p 0; 0; Introduction to Computer Science, Shimon Schocken slide 17 Proll clss digrm Worker (bstrct) - nme : to : p : double (bstrct) HourlWorker - hourlrte : double - hoursworked : ddhours ( morehours) : to : p : double Emploee - slr : double to : p : double Volunteer to : p : double Eecutive - bonus : double setbonus (double bonus) : to : p : double Introduction to Computer Science, Shimon Schocken slide 18 Intorduction to Computer Science IDC Herzli Shimon Schocken

Sub-clssing Worker: HourlWorker bse-clss generic generic bstrct bstrct clss clss Worker Worker dt: dt: nme; nme; dt dt comes comes here here worker worker Worker Worker ( ( nme) nme).nme.nme nme; nme; to to "Nme: "Nme: " " nme; nme; Ps Ps bstrct bstrct double double p p ; ; clss clss HourlWorker HourlWorker etends etends Worker Worker double double hourlrte; hourlrte; hoursworked; hoursworked; sub-clss hourl worker HourlWorker ( nme,double hourlrte) super(nme);.hourlrte hourlrte;.hoursworked 0; ddhours ( hours) hoursworked hours; to super.to "\n" "Current hours: " hoursworked "\n" "Hourl rte: " hourlrte; double p double pment hoursworked * hourlrte; hoursworked 0; pment; Introduction to Computer Science, Shimon Schocken slide 19 Proll clss digrm Worker (bstrct) - nme : to : p : double (bstrct) HourlWorker - hourlrte : double - hoursworked : ddhours ( morehours) : to : p : double Emploee - slr : double to : p : double Volunteer to : p : double Eecutive - bonus : double setbonus (double bonus) : to : p : double Introduction to Computer Science, Shimon Schocken slide 20 Intorduction to Computer Science IDC Herzli Shimon Schocken

Sub-clssing Worker: Emploee bse-clss generic generic bstrct bstrct clss clss Worker Worker sub-clss n n emploee emploee clss clss Emploee Emploee etends etends Worker Worker dt: dt: nme; nme; dt dt comes comes here here worker worker Worker Worker ( ( nme) nme).nme.nme nme; nme; to to "Nme: "Nme: " " nme; nme; double double slr; slr; n n emploee emploee Emploee Emploee ( ( nme, nme, double double slr) slr) super(nme); super(nme);.slr.slr slr; slr; to to super.to super.to "\n" "\n" "Monthl "Monthl slr: slr: " " slr; slr; Ps Ps bstrct bstrct double double p p ; ; Monthl Monthl pment pment emploee. emploee. double double p p slr; slr; Introduction to Computer Science, Shimon Schocken slide 21 Proll clss digrm Worker (bstrct) - nme : to : p : double (bstrct) HourlWorker - hourlrte : double - hoursworked : ddhours ( morehours) : to : p : double Emploee - slr : double to : p : double Volunteer to : p : double Eecutive - bonus : double setbonus (double bonus) : to : p : double Introduction to Computer Science, Shimon Schocken slide 22 Intorduction to Computer Science IDC Herzli Shimon Schocken

Sub-clssing Emploee: Eecutive bse-clss clss clss Emploee Emploee etends etends Worker Worker double double slr; slr; n n emploee emploee Emploee Emploee ( ( nme, nme, double double slr) slr) super super (nme); (nme);.slr.slr slr; slr; to to super.to super.to "\n" "\n" "Monthl "Monthl slr: slr: slr; slr; Monthl Monthl pment pment emploee. emploee. double double p p slr; slr; clss clss Eecutive Eecutive etends etends Emploee Emploee double double bonus; bonus; sub-clss Eecutive. Eecutive ( nme, double slr) super(nme, slr); bonus 0; Awrds bonus to eecutive. setbonus (double bonus).bonus bonus; to super.to "\n" "Bonus: " bonus; Monthl pment eecutive double p double pment super.p bonus; bonus 0; pment; Introduction to Computer Science, Shimon Schocken slide 23 Proll clss digrm (complete) PRollDemo min (rgs : []) : WorkForce workers : Worker[] genertedte : genertepments : Worker (bstrct) - nme : to : p : double (bstrct) HourlWorker - hourlrte : double - hoursworked : ddhours ( morehours) : to : p : double Emploee - slr : double to : p : double Volunteer to : p : double Eecutive - bonus : double setbonus (double bonus) : to : p : double Introduction to Computer Science, Shimon Schocken slide 24 Intorduction to Computer Science IDC Herzli Shimon Schocken

WorkForce: collection Worker objects workers workers nd nd ir ir pments pments clss clss WorkForce WorkForce Worker[] Worker[] workers; workers; WorkForce WorkForce demo demo rr rr 6 6 workers. workers. workers workers Worker[6]; Worker[6]; workers[0] workers[0] Eecutive("Jne", Eecutive("Jne", 7500); 7500); workers[1] workers[1] Emploee Emploee ("Crl", ("Crl", 3000); 3000); workers[2] workers[2] Emploee Emploee ("Wood", ("Wood", 2500); 2500); workers[3] workers[3] HourlWorker HourlWorker ("Dine", ("Dine", 10); 10); workers[4] workers[4] Volunteer Volunteer ("Norm"); ("Norm"); workers[5] workers[5] Volunteer Volunteer ("Cliff"); ("Cliff"); Generte some demo work dt genertedt ((Eecutive) workers[0]).setbonus(500); ((HourlWorker) workers[3]).ddhours(40); ((HourlWorker) workers[3]).ddhours(10); Ps ll workers genertepments Net slide. The construction different workers depends on ir tpes: different sub-tpes hve different constructors. Introduction to Computer Science, Shimon Schocken slide 25 Ping workers, polmorphicll clss clss PRollDemo PRollDemo sttic sttic min min ([] ([] rgs) rgs) WorkForce WorkForce workforce workforce WorkForce; WorkForce; Code Code continues continues from from previous previous slide slide workforce.genertedt; workforce.genertedt; workforce.genertepments; workforce.genertepments; Ps Ps ll ll workers workers genertepments genertepments ( ( j j 0; 0; j j < < workers.length; workers.length; j) j) Pr Pr worker's worker's dt dt Sstem.out.prln Sstem.out.prln (workers[j]); (workers[j]); Compute Compute nd nd pr pr monthl monthl pment pment Sstem.out.prln("P Sstem.out.prln("P due: due: workers[j].p); workers[j].p); Sstem.out.prln; Sstem.out.prln; Polmorphic method invoction Introduction to Computer Science, Shimon Schocken slide 26 Intorduction to Computer Science IDC Herzli Shimon Schocken

Outline Polmorphism Emples polmorphic solutions: Fighting rm Proll Pbrush Revisiting erfces Introduction to Computer Science, Shimon Schocken slide 27 Heterogeneous collections A heterogeneous collection is clss tht cn contin objects rbitrr tpes Populr heterogeneous collection clsses in Jv: jv.util.arrlist Jv.util.Vector rr Animl[] Animl[] zoo zoo Animl[4]; Animl[4]; zoo[0] zoo[0] Pig; Pig; zoo[1] zoo[1] Pig; Pig; zoo[2] zoo[2] Mouse; Mouse; zoo[3] zoo[3] Dog; Dog; Properties n ArrList / Vector: Holds n ordered collection objects ( n tpe) A growble, fleible, nd untped version n rr Objects cn be dded using n inde, or not The collection size grows nd shrinks s needed. Vector Vector Vector zoo zoo Vector; Vector; zoo.ddelement( zoo.ddelement( Pig); Pig); zoo.ddelement( zoo.ddelement( Pig); Pig); zoo.ddelement( zoo.ddelement( Mouse); Mouse); zoo.ddelement( zoo.ddelement( Dog); Dog); zoo.ddelement(17); zoo.ddelement(17); zoo.ddelement( It s zoo.ddelement( It s rining ); rining ); zoo.remove(2); zoo.remove(2); zoo.insertelementat( zoo.insertelementat( Dog,2) Dog,2) Introduction to Computer Science, Shimon Schocken slide 28 Intorduction to Computer Science IDC Herzli Shimon Schocken

Heterogeneous collections re not tpe sfe Vector Vector zoo zoo Vector; Vector; zoo.ddelement( zoo.ddelement( Pig); Pig); zoo.ddelement( zoo.ddelement( Pig); Pig); zoo.ddelement( zoo.ddelement( Mouse); Mouse); zoo.ddelement( zoo.ddelement( Dog); Dog); zoo.ddelement(17); zoo.ddelement(17); zoo.ddelement( It s zoo.ddelement( It s rining ); rining ); Vector (like or heterogeneous collection clsses) is tpe unsfe Object obj zoo.elementat(j); if (obj instnceof Animl) Animl (Animl) obj; Now cn be used s n niml Bee using n item tken from Vector, ou must check its tpe nd n cst ccordingl. Introduction to Computer Science, Shimon Schocken slide 29 Tped collections Jv llows to crete tped collections, using snt CollectionNme < TpeNme > Vector<Animl> Vector<Animl> zoo zoo Vector; Vector; zoo.ddelement( Pig); zoo.ddelement( Pig); zoo.ddelement( Mouse); zoo.ddelement( Dog); zoo.ddelement(17); zoo.ddelement( It s rining ); Will not compile Will not compile With tped collection, re is no need to check nd cst: Animl zoo.elementat(j); Introduction to Computer Science, Shimon Schocken slide 30 Intorduction to Computer Science IDC Herzli Shimon Schocken

Pbrush ppliction The tsk: Build progrm tht llows users to crete nd mnge simple pictures. Ech picture is mde generic geometricl figures like rectngle, circle, tringle, etc. The sstem should llow: Creting picture Adding geometric shpes to picture Deleting figures Moving figures Resizing figures Etc. It should be possible to tke picture nd Store it in file Ship it to nor computer Displ it on n given screen. Introduction to Computer Science, Shimon Schocken slide 31 Picture API clss clss Picture Picture Picture Picture dd dd ( ( figure) figure) delete delete ( ( figure) figure) drw drw entire entire picture picture erse erse entire entire picture picture Or Or Picture-level Picture-level methods. methods. The PBrush ppliction GUI: We ssume tht user is using some GUI to drw shpes on screen When user is done drwing shpe, we dd shpe to picture. Introduction to Computer Science, Shimon Schocken slide 32 Intorduction to Computer Science IDC Herzli Shimon Schocken

API bstrct bstrct clss clss ( (,, height) height) Color Color getlinecolor getlinecolor is n bstrct clss: setlinecolor setlinecolor (Color (Color c) c) bstrct bstrct drw drw It provides templte deriving sub-clsses tht methods methods represent boed geometric shpes clss Tringle etends, width Rectngle etends height n equilterl tringle given size Tringle (, double size) drw clss Circle etends Tringle etends circle given rdius Circle (, double rdius) drw One such clss ever generic figure. Circle etends Introduction to Computer Science, Shimon Schocken slide 33 Client code emple: drwing stick house clss clss PBrushDemo PBrushDemo sttic sttic min([] min([] rgs) rgs) Picture Picture picture picture Picture; Picture; Build Build wll, wll, door, door, nd nd ro ro 100; 100; 200; 200; Rectngle Rectngle wll wll Rectngle(, Rectngle(, 150, 150, 200); 200); Rectngle Rectngle door door Rectngle( Rectngle( 75, 75, 100, 100, 40, 40, 100); 100); Tringle Tringle ro ro Tringle(, Tringle(, 150); 150); ro.setlinecolor(color.red); ro.setlinecolor(color.red); picture.dd(wll); picture.dd(wll); (0,0) picture.dd(door); picture.dd(door); picture.dd(ro); picture.dd(ro); 100 200 Build Build stick stick fence fence 200; 200; 120; 120; ( ( i i 0; 0; i i < < 10; 10; i) i) picture.dd( picture.dd( Rectngle(, Rectngle(, 10, 10, 80)); 80)); 20; 20; Build Build 2 2 horizontl horizontl bems bems (omitted) (omitted) The pproch: A drwing is implemented s Picture, to which we dd figures like Rectngle, Tringle, etc. 200 120 picture.drw; picture.drw; An erctive version progrm would redrw picture ech time figure is built. Introduction to Computer Science, Shimon Schocken slide 34 Intorduction to Computer Science IDC Herzli Shimon Schocken

Behind scene: clss bstrct bstrct clss clss, width Top-left Top-left corner corner figure s figure s bo bo protected protected,;,; height Dimensions Dimensions figure s figure s bo bo protected protected Defult Defult color color figure s figure s outline outline Color Color linecolor linecolor Color.blck; Color.blck; An bstrct clss, Provides templte deriving sub-clsses tht represent boed geometricl shpes Rectngle etends ( (,, height) height).. ; ;.. ; ;.width.width width; width;.height.height Tringle etends Color Color getlinecolor getlinecolor linecolor; linecolor; setlinecolor(color setlinecolor(color c) c) linecolor linecolor c; c; methods methods (net (net slide) slide) Circle etends Introduction to Computer Science, Shimon Schocken slide 35 Behind scene: clss bstrct bstrct clss clss, width protected protected,, Continued Continued from from previous previous slide slide...... height Checks Checks if if (,) (,) is is within within figure's figure's bo bo boolen boolen contins contins ( (,, ) ) > >.. && && < <.. width width && && > >.. && && < <.. Drws Drws figure figure bstrct bstrct drw drw ; ; methods methods Rectngle etends Tringle etends is bstrct bse clss ll sub-tpes It defines common dt nd behvior tht ech boed geometric figure must hve. Circle etends Introduction to Computer Science, Shimon Schocken slide 36 Intorduction to Computer Science IDC Herzli Shimon Schocken

Sub-clssing : Clss Rectngle bse bstrct bstrct clss clss protected protected,, Color Color linecolor linecolor Color.blck; Color.blck; ( (,, height) height) Color Color getlinecolor getlinecolor setlinecolor setlinecolor (Color (Color c) c) boolen boolen contins contins ( (,, ) ) bstrct bstrct drw drw ; ; Or Or methods methods import import turtle.turtle; turtle.turtle; clss clss Rectngle Rectngle etends etends sub Rectngle Rectngle ( (,, height) height) super(, super(, height); height); drw drw Turtle Turtle per per Turtle; Turtle; per.setlinecolor(getlinecolor); per.setlinecolor(getlinecolor); per.setloction(, per.setloction(, ); ); per.tildown; per.tildown; per.moveforwrd(width); per.moveforwrd(width); per.turnright(90); per.turnright(90); per.moveforwrd(height); per.moveforwrd(height); per.turnright(90); per.turnright(90); per.moveforwrd(width); per.moveforwrd(width); per.turnright(90); per.turnright(90); per.moveforwrd(height); per.moveforwrd(height); per.hide; per.hide; Introduction to Computer Science, Shimon Schocken slide 37 Sub-clssing : clss Tringle bse bstrct bstrct clss clss protected protected,, Color Color linecolor linecolor Color.blck; Color.blck; ( (,, height) height) Color Color getlinecolor getlinecolor setlinecolor setlinecolor (Color (Color c) c) boolen boolen contins contins ( (,, ) ) bstrct bstrct drw drw ; ; Or Or methods methods sub import import turtle.turtle; turtle.turtle; clss clss Tringle Tringle etends etends n n equilterl equilterl tringle tringle whose whose top-left top-left corner corner is is,, Tringle Tringle ( (,, size) size) super(,size, super(,size, Mth.sqrt(3/4)*size); Mth.sqrt(3/4)*size); drw drw Turtle Turtle per per Turtle; Turtle; per.setlinecolor(getlinecolor); per.setlinecolor(getlinecolor); per.setloction( per.setloction( height); height); per.tildown; per.tildown; per.turnleft(30); per.turnleft(30); per.moveforwrd(width); per.moveforwrd(width); per.turnleft(120); per.turnleft(120); per.moveforwrd(width); per.moveforwrd(width); per.turnleft(120); per.turnleft(120); per.moveforwrd(width); per.moveforwrd(width); per.hide; per.hide; Introduction to Computer Science, Shimon Schocken slide 38 Intorduction to Computer Science IDC Herzli Shimon Schocken

clss Picture import import jv.util.vector; jv.util.vector; clss clss Picture Picture Vector Vector figures; figures; Picture Picture.figures.figures Vector; Vector; dd( dd( figure) figure) figures.ddelement(figure); figures.ddelement(figure); drw drw ( ( i i 0; 0; i i < < figures.size; figures.size; i) i) ( ( figures.elementat(i)).drw; figures.elementat(i)).drw; PBrush clients crete pictures b: Constructing picture Constructing vrious figures Adding figures to picture Thus, it mkes sense to implement picture s heterogeneous collection. Note csting we re deling with tpe unsfe collection (Vector) Polmorphic method invoction Introduction to Computer Science, Shimon Schocken slide 39 The PBrush ppliction: clss digrm PBrushDemo min (bstrct) Picture - figures : Vector dd( figure) : drw : #, : # width, height : - linecolor : Color drw : (bstrct) contins(, ) : boolen... Rectngle drw Tringle drw... Circle drw Introduction to Computer Science, Shimon Schocken slide 40 Intorduction to Computer Science IDC Herzli Shimon Schocken

Outline Polmorphism Emples polmorphic solutions: Fighting rm Proll Pbrush Revisiting erfces Introduction to Computer Science, Shimon Schocken slide 41 Using erfces to crete generic solutions The Jv clss librr fetures comprble erfce. In emple we crete comprble erfce our own: erfce erfce Comprble Comprble boolen boolen gt gt (Comprble (Comprble or); or); boolen boolen lt lt (Comprble (Comprble or); or); boolen boolen equls equls (Comprble (Comprble or); or); Emple clss tht implements Comprble: clss clss Dte Dte implements implements Comprble Comprble d d month, month, er; er; Dte Dte ( ( d d month, month, er) er).d.d d; d;.month.month month; month;.er.er er; er; to to d d "/" "/" month month "/" "/" er; er; boolen boolen gt gt (Comprble (Comprble or) or) Dte Dte d d (Dte) (Dte) or; or; if if (er (er!! d.er) d.er) er er > > d.er; d.er; if if (month (month!! d.month) d.month) month month > > d.month; d.month; d d > > d.d; d.d; lt lt nd nd equls equls implementtions implementtions re re similr similr Introduction to Computer Science, Shimon Schocken slide 42 Intorduction to Computer Science IDC Herzli Shimon Schocken

Generic sorter clss clss Sorter Sorter sttic sttic selectionsort selectionsort (Comprble[] (Comprble[] ) ) ( ( j j 0; 0; j j < <.length-1;.length-1; j) j) min min j; j; ( ( k k j1; j1; k k < <.length;.length; k) k) if if ( ( [min].gt([k]) [min].gt([k]) ) ) min min k; k; if if (min (min!! j) j) Comprble Comprble temp temp [min]; [min]; [min] [min] [j]; [j]; [j] [j] temp; temp; Insted sorting n rr specific dt tpe, we re willing to sort n rr Comprble objects Insted using > we use gt, since we know tht Comprble objects must implement it. When declring vrible tht holds comprble vlue, we cst it s Comprble Impliction: Sorter.selectionSort cn now be used to sort objects tht come from n clss tht implements Comprble Introduction to Computer Science, Shimon Schocken slide 43 Generic sorter clss clss DteSortDemo DteSortDemo sttic sttic min min ([] ([] rgs) rgs) Dte[] Dte[] dtes dtes Dte[4]; Dte[4]; dtes[0] dtes[0] Dte(17, Dte(17, 2, 2, 2009); 2009); dtes[1] dtes[1] Dte(1, Dte(1, 4, 4, 1954); 1954); dtes[2] dtes[2] Dte(20, Dte(20, 2, 2, 2009); 2009); dtes[3] dtes[3] Dte(3, Dte(3, 11, 11, 1967); 1967); Sorter.selectionSort(dtes); Sorter.selectionSort(dtes); (Dte (Dte d d : : dtes) dtes) Sstem.out.prln(dtes[j]); Sstem.out.prln(dtes[j]); Introduction to Computer Science, Shimon Schocken slide 44 Intorduction to Computer Science IDC Herzli Shimon Schocken