OOP Subtyping. Lecture 20

Similar documents
Mouse / Keyboard Events & Anonymous Functions. Lecture 19

Java Object Oriented Design. CSC207 Fall 2014

CS-202 Introduction to Object Oriented Programming

Default Parameters and Shapes. Lecture 18

What is Inheritance?

CIS 110: Introduction to computer programming

JAVA MOCK TEST JAVA MOCK TEST II

25. Generic Programming

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

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.

More on inheritance CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014

Super-Classes and sub-classes

Inheritance and object compatibility

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

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Programming Languages and Techniques (CIS120)

CH. 2 OBJECT-ORIENTED PROGRAMMING

Inheritance and Interfaces

CS Programming I: Inheritance

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Introduction to Inheritance

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

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

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Object-Oriented Programming. Lecture 17

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

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

Basic Object-Oriented Concepts. 5-Oct-17

Inheritance (Outsource: )

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

Comments are almost like C++

Programming Languages and Techniques (CIS120)

An Brief Introduction to a web browser's Document Object Model (DOM) Lecture 20 COMP110 Spring 2018

Using Inheritance to Share Implementations

Inheritance. A key OOP concept

C++ Important Questions with Answers

Rules and syntax for inheritance. The boring stuff

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

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

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Inheritance and Polymorphism

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

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

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Classes and Inheritance Extending Classes, Chapter 5.2

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

Programming Languages and Techniques (CIS120)

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

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

CSE143 Notes for Monday, 7/06/15

2. The object-oriented paradigm!

+ Questions about Assignment 5?

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

OVERRIDING. 7/11/2015 Budditha Hettige 82

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

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

CS 11 java track: lecture 3

ITI Introduction to Computing II

Practice for Chapter 11

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

Inheritance -- Introduction

Making New instances of Classes

CS 251 Intermediate Programming Inheritance

Inheritance and Polymorphism

Intro to Computer Science 2. Inheritance

1 Shyam sir JAVA Notes

In this lab, you will be given the implementation of the classes GeometricObject, Circle, and Rectangle, as shown in the following UML class diagram.

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Review questions. Review questions, cont d. Class Definition. Methods. Class definition: methods. April 1,

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

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

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

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

ITI Introduction to Computing II

CS260 Intro to Java & Android 03.Java Language Basics

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Programming Languages and Techniques (CIS120)

CS 520 Theory and Practice of Software Engineering Fall 2018

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

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

Methods Common to all Classes

The software crisis. 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

Programming Languages and Techniques (CIS120)

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

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

Advanced Placement Computer Science. Inheritance and Polymorphism

Inheritance - Assignment5

Inheritance. For example, to zoom in on the deer family (cervid), we could make a tree like the following.

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

Chapter 9 Inheritance

Lecture Notes Chapter #9_b Inheritance & Polymorphism

COMP 250 Fall inheritance Nov. 17, 2017

Data Structures and Other Objects Using C++

CS1150 Principles of Computer Science Objects and Classes

Transcription:

OOP Subtyping Lecture 20

Announcements WS05 - Posted yesterday, due Wednesday 11/8 at 11:59pm Explores recursion and object-oriented programming fundamentals

Warm-up: What is printed? interface Transform<T, U> { (input: T): U; let t: Transform<number, number>; let r: number = random(0, 2); if (r === 0) { t = function(n: number): number { return n * r; ; else if (r === 1) { t = function(n: number): number { return n + r; ; else { t = function(n: number): number { return n - r; ; print(t(0));

Classes establish Data Types A class tells you: 1) What properties objects of that type have 2) How to construct new values of that type (called objects) 3) What methods you can call on objects of that type

How can we add different types of Shapes to a Group? The parameter type of the add method is SVGElement!?!? But we've been able to add Shapes to it! Both Rectangle and Circle Shapes! How? Because: Shape is an SVGElement Rectangle is a Shape Circle is a Shape Today we'll learn how to write a class that is a subtype of another class.

Graphics Library Type Hierarchy SVGElement Shape Group Line Rectangle Circle

A class can extend another class to establish a more specific type. Classes can form a class hierarchy Like a taxonomy in biology When a class (A) is extended by another class (B)... an object of type B is an object of type A an object of type A is not necessarily of type B class Square extends Rectangle "A Square is a rectangle, but a Rectangle is not necessarily a Square."

Terminology Shape is the supertype of Line, Rectangle, Circle. Also called a superclass. SVGElement Shape Group Line Rectangle Circle

Terminology Line is a subtype of Shape. Also known as a subclass. SVGElement Shape Group Line Rectangle Circle

We can extend built-in classes. SVGElement Shape Group Line Rectangle Circle Dot We're going to extend the hierarchy today! GrowingDot MovingDot

Defining a Subclass class <Subclass> extends <Superclass> { When defining a new class, you can extend an existing class by using the keyword extends followed by the superclass' name When a class is extended, the subclass automatically has the properties, constructor, and methods of the superclass. When extending a class, you can: 1. Introduce additional, new properties or methods to the subclass. This works no differently than adding them to a standalone class! 2. Override existing methods or constructors of the superclass. There are a few nuances in doing this that we'll explore today. You cannot remove properties, constructor, or methods.

Follow-along: Declare a Dot subclass of Circle In lec20 / dots-script.ts We're going to introduce the notion of a "Dot" A Dot will be a Circle, but with some additional capabilities Let's begin by establishing Dot without any new capabilities: class Dot extends Circle {

Hands-on #1 In the main function, assign to the window object's onclick event an anonymous MouseEventHandler function: window.onclick = function(event: MouseEvent): void { //... ; 1. In it, declare a new Dot type variable named dot 2. Initialize it to a new Dot object - Hint: it has Circle's constructor! 1. radius: 30 2. cx: event.clientx 3. cy: event.clienty 3. Add the dot to the scene Group Save, refresh, and when you click a dot should appear. Check-in on PollEv!

function main(): void { scene = initscene(); window.onclick = function(event: MouseEvent): void { let dot: Dot; dot = new Dot(30, event.clientx, event.clienty); scene.add(dot); ;

Adding Methods to a Subclass Methods can be added to a subclass the same as to a regular class. In doing so, only objects of the subclass' type have the method You are not changing the superclass in any way. Let's add a method to our Dot that sets its fill to a random color. Then, before adding it to our scene in the click handler, let's call it! class Dot extends Circle { fillrandom(): void { this.fill = new Color(Math.random(), Math.random(), Math.random());

Subclass Constructor Rule: A subclass constructor must call super Constructor First When defining a subclass constructor, there is something you must always do: call the superclass' constructor first. Why? The superclass' constructor is responsible for initializing the properties it defines. How? Inside of a subclass constructor, a special keyword named super refers to the superclass' constructor. You must call it with the correct arguments.

Adding a constructor to Dot Suppose we wanted all Dots to have an initial radius of 30 and to have a random starting fill color. We can ensure this by declaring a constructor for Dot (below). Notice the first thing we needed to do was call the super class' (Circle's) constructor! class Dot extends Circle { constructor(cx: number, cy: number) { super(30, cx, cy); this.fillrandom(); // Elided

Project Goal: Update a Dot's Color over time We'd like our Dot (and other special kinds of Dots we'll build next) to update and change as time passes Let's add an update method to Dot that just calls fillrandom for now... update(): void { this.fillrandom();

How can we call update() on every Dot in our scene Group? Every Dot we create is being added to the Group named scene This is possible because a Dot is an SVGElement Logically: Dot is a Circle, Circle is a Shape, Shape is an SVGElement We can access the children of our scene group, but we have a problem. How do we know if any given SVGElement is actually a Dot? We must test for it!

The instanceof Operator The instanceof Operator will test a value to see if that value is an instance of ("object of") some given type. For example: let child: SVGElement = new Dot(0, 0); child instanceof Dot // Evaluates to true child = new Rectangle(10, 10); child instanceof Dot // Evaluates to false Intuition: A Dot is always an SVGElement but an SVGElement is not necessarily a Dot.

Using a superclass type as a subclass We can't call update on child here: let child: SVGElement = scene.children[i]; child.update(); // ERROR Why? Because we don't know whether child is actually a Dot! Only objects of type Dot have an update method. How can we fix this? We can test for it (just like we tested for null): let child: SVGElement = scene.children[i]; if (child instanceof Dot) { child.update(); // OK

Let's update all Dot objects every second First, we need to import SVGElement from "introcs/graphics" Then we'll loop through each child SVGElement in the scene and test if it's a Dot If so, we'll call the update method on it function tick(): void { for (let i: number = 0; i < scene.children.length; i++) { let child: SVGElement = scene.children[i]; if (child instanceof Dot) { child.update(); // At the end of the the main function: setinterval(tick, 1000);

Project Goal: What if we wanted to call each Dot's update method 60 times per second? This will be important for other kinds of dots that Move or Grow to animate smoothly How can we ensure that each regular Dot only changes colors once per second? We'll keep track of every project's "age" in terms of # of updates and every 60 updates we'll change it's color. We'll also change the setinterval function's time argument to be 1000 / 60 (1000 milliseconds / 60 frames per second)

Adding Properties to a Subclass Properties can be added to a subclass the same as to a regular class. In doing so, only objects of the subclass' type have the property You are not changing the superclass in any way. Let's add an age property to Dot to keep track of the number of times it has been updated (below). Then, we'll change our update method (next slide). class Dot extends Circle { age: number = 0; // Constructor, Methods Elided

class Dot extends Circle { age: number = 0; // Constructor, Other Methods Elided update(): void { this.age += 1; if (this.age % 60 === 0) { this.fillrandom();

Further Subtyping with GrowingDot Let's establish a new kind of Dot, a GrowingDot GrowingDot will override Dot's update method and instead, when a GrowingDot's update method is called, its radius will be based on its age. class GrowingDot extends Dot { update(): void { this.r = 30 + this.age % 60; But wait! The age property was being updated in Dot's update method. Do we need to reimplement that logic?

Calling an overridden method from a subclass No, we can make use of the superclass' overridden method by calling it from the subclass: class GrowingDot extends Dot { update(): void { super.update(); this.r = 30 + this.age % 60; This is saying, "hey superclass (Circle), call your update method first." This is useful when we just want to extend the functionality of a superclass' method, we don't want to replace it completely.

Let's add GrowingDots instead of Dots onclick let dot: Dot = new GrowingDot(event.clientX, event.clienty);

Typing with a Superclass (1 / 3) A subtype value can be assigned to a supertype, but not vice-versa OK: let dot: Dot = new GrowingDot(event.clientX, event.clienty); Not OK: let dot: GrowingDot = new Dot(event.clientX, event.clienty);

Typing with a Superclass (2 / 3) Suppose we have the following code: let dot: Dot; dot = new GrowingDot(event.clientX, event.clienty); dot.update(); What update method gets called? Dot's or GrowingDot's? GrowingDot's! What? How? Why?

Typing with a Superclass (3 / 3) The type of variable dot is Dot let dot: Dot; dot = new GrowingDot(event.clientX, event.clienty); dot.update(); So, we know dot has an update method and know its params/return type but we don't necessarily know how it will update when we tell it to update. This is because the dot variable can also refer to a more specific kind of Dot object (in this example: a GrowingDot). A type of a value (Dot) tells you what methods you're allowed to call. An object's construction determines the method that gets called. When a method call occurs on any object, the call is sent to the class the object was actually constructed with.

A Type tells you what it can do, not how it does it The type of a value tells you how you are allowed to interact with that value in code If it is a primitive value type (number, string, boolean) Then you can use primitive operations If it is an array of some other type Then you can use the index operator a[<index>] If it is a function-type value Then you know what parameters it requires and it's return type You may not know what function will actually be called when you call it (As shown in the PollEverywhere example. Also fundamental to how filter/map/reduce work.) If it is an object-type value Then you know its class which tells you its properties, constructor, and methods You also know what methods it has, their parameters, and their return type You may not know what method will actually be called when you call it

Hands-on: Add Another Subtype of Dot 1. Define a new class named MovingDot that extends Dot 2. Like GrowingDot, override the update method of Dot. Define a method named update with no parameters and a void return type. 3. It's update method should: 1. Call the update method of its super class. 2. If the remainder of dividing its age property by 60 is 0 (each second), then Set its cx property to be the current cx value + (Math.random() * 50 25) Set its cy property to be the current cy value + (Math.random() * 50 25) 4. Make it such that clicking on the window adds a MovingDot instead of a GrowingDot 5. Check-in when you have MovingDot objects jumping around on screen on PollEv.

class MovingDot extends Dot { update(): void { super.update(); if (this.age % 60 === 0) { this.cx += Math.random() * 100-50; this.cy += Math.random() * 100-50;

Together: Adding Random Types of Dots Let's change our onclick handler to pick a number at random between 0 and 2, inclusive Based on that random number, we'll add one of our 3 kinds of Dot objects to the scene window.onclick = function(event: MouseEvent): void { let choice: number = random(0, 2); let dot: Dot; if (choice === 0) { dot = new MovingDot(event.clientX, event.clienty); else if (choice === 1) { dot = new Dot(event.clientX, event.clienty); else { dot = new GrowingDot(event.clientX, event.clienty); scene.add(dot); ;

Polymorphism & Dynamic Dispatch (1 / 2) Let's revisit the logic of our tick function for (let i: number = 0; i < scene.children.length; i++) { let child: SVGElement = scene.children[i]; if (child instanceof Dot) { child.update(); Notice, we didn't change this logic once we added new kinds of Dots! And it still worked by calling GrowingDot's and MovingDot's update methods! We can continue introducing additional subtypes of Dot with their own update logic and tick's logic can remain the same. This is thanks to the fact that every subtype of dot is a Dot and, therefore, has the ability to update. How it updates is based on the class/subclass used to construct the Dot object

Polymorphism & Dynamic Dispatch (2 / 2) if (child instanceof Dot) { child.update(); Given the following method call: child.update(); Until you know what class the child object actually is, you cannot know which update method will be called here. This is called "dynamic dispatch". This single method call could possibly jump to 1 + # of Dot subclasses different methods. This is the idea of "polymorphism". That single child object can take many different forms by way of subclasses.