CSE 341 Lecture 26 OOP, prototypes, and inheritance slides created by Marty Stepp

Slides:



Advertisements
Similar presentations
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Advertisements

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
CSE 143 Lecture 3 Inheritance slides created by Marty Stepp
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Programming in Scala Chapter 1. Scala: both object-oriented and functional Scala blends –object-oriented and –functional programming in a –statically.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Methods and Constructors reading: self-checks: #1-12.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Packages. Package A package is a set of related classes Syntax to put a class into a package: package ; public class { …} Two rules:  A package declaration.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Object Oriented JavaScript. JavaScript Really only 4 types in JavaScript – number, string, boolean – Object (includes arrays) Remember that an object.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
CSE 143 Lecture 23 Polymorphism; the Object class read slides created by Marty Stepp and Ethan Apter
1 Object state: fields. Fields field: A variable inside an object that represents part of its internal state.  Each object will have its own copy of.
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
TeachJava! 2003 Corky Cartwright Dung Nguyen Stephen Wong Charlie Reis, James Hsia, Peter Centgraf.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
Object Oriented JavaScript. JavaScript Really only 4 types in JavaScript – number, string, boolean – Object (includes arrays) Remember that an object.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
BY:- TOPS Technologies
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Methods and Constructors reading: self-checks: #1-12.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Constructors; Encapsulation reading: self-checks: #13-18,
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Building Java Programs
Chapter 11 Inheritance and Polymorphism
COP 3331 Object Oriented Analysis and Design Chapter 5 – Classes and Inheritance Jean Muhammad.
Overloading and Constructors
Chapter 9 Inheritance and Polymorphism
CSE 331 Cloning objects slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
null, true, and false are also reserved.
Java Programming Language
Building Java Programs
The Building Blocks Classes: Java class library, over 1,800 classes:
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Building Java Programs
Building Java Programs
CSE 142 Lecture Notes Defining New Types of Objects
Building Java Programs
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Building Java Programs
Building Java Programs
Building Java Programs
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Building Java Programs
Lecture 8-2: Object Behavior (Methods) and Constructors
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
Building Java Programs
Chapter 11 Inheritance and Encapsulation and Polymorphism
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Presentation transcript:

CSE 341 Lecture 26 OOP, prototypes, and inheritance slides created by Marty Stepp

2 How to get a "class"? What if we want to create a class, not just one object?  JavaScript, unlike Java, does NOT have classes  we could emulate a constructor with a function: // Creates and returns a new Point object. function constructPoint(xValue, yValue) { // bad code return { x: xValue, y: yValue, distanceFromOrigin: function() { return Math.sqrt(this.x * this.x + this.y * this.y; } }; } > var p = constructPoint(4, -3);

3 Problems with pseudo-constructor function constructPoint(xValue, yValue) { // bad code return { x: xValue, y: yValue, distanceFromOrigin: function() { return Math.sqrt(this.x * this.x + this.y * this.y; } }; }  ugly  doesn't match the " new " syntax we're used to  wasteful; stores a separate copy of the distanceFromOrigin method in each Point object

4 Functions as constructors // Constructs and returns a new Point object. function Point(xValue, yValue) { this.x = xValue; this.y = yValue; this.distanceFromOrigin = function() { return Math.sqrt(this.x * this.x + this.y * this.y); }; } > var p = new Point(4, -3);  a constructor is just a normal function!  called with new like in Java

5 Functions as constructors in JavaScript, any function can be used as a constructor!  by convention, constructors' names begin in uppercase  when a function is called w/ new, it implicitly returns this function Point(x, y) { this.x = x; this.y = y; }  all global "classes" ( Number, String, etc.) are functions acting as constructors, that contain useful properties

6 Functions as constructors any function can be called as a constructor or a function when any function called with new, JavaScript:  creates a new empty anonymous object  uses the new empty object as this within the call  implicitly returns the new object at the end of the call if you call a "constructor" without new, this refers to the global object instead  what happens if our "constructor" is called this way? > var p = Point(4, -3);

7 Prototypes prototype: an ancestor of a JavaScript object  like a "super-object" instead of a superclass  a parent at the object level rather than at the class level

8 Prototypes every object contains a reference to its prototype  default: Object.prototype ; strings → String.prototype ; etc. a prototype can have a prototype, and so on  an object "inherits" all methods/data from its prototype(s)  doesn't have to make a copy of them; saves memory  prototypes allow JavaScript to mimic classes, inheritance

9 Functions and prototypes // also causes Point.prototype to be defined function Point(xValue, yValue) {... } every function stores a prototype object property in it  example: when we define our Point function (constructor), that creates a Point.prototype  initially this object has nothing in it ( {} )  every object you construct will use the function's prototype object as its prototype –e.g. every new Point object uses Point.prototype

10 How constructors work when any function called with new, JavaScript:  creates a new empty anonymous object  uses the new empty object as this within the call  attaches the function's.prototype property to the new object as its internal prototype  implicitly returns the new object at the end of the call

11 The prototype chain var p1 = new Point(4, -3); when you ask for a property (or method) in an object, JS:  sees if the object itself contains that property  if not, recursively checks the object's prototype for it  if not found, continues up the "prototype chain" until it finds the property or gives up with undefined

12 Augmenting a type via prototypes // adding a method to the prototype function.prototype.name = function(params) { statements; }; Point.prototype.distanceFromOrigin = function() { return Math.sqrt(this.x * this.x + this.y * this.y); }; adding a property to a prototype will give it to all objects that use that prototype  better than manually adding each method to each object

13 What goes in a prototype? generally only methods and constants (variables)  not objects' fields!  can also add "static" methods meant to be called on the prototype itself, e.g. Math.abs What would happen if we put the x and y fields in Point.prototype ? Exercise: Add distance and toString methods.

14 Exercise solutions // Distance between this point and the given point. Point.prototype.distance = function(p) { var dx = this.x - p.x; var dy = this.y - p.y; return Math.sqrt(dx * dx + dy * dy); }; // A string version of this object, e.g. "(3, -4)". Point.prototype.toString = function() { return "(" + this.x + ", " + this.y + ")"; };

15 Modifying built-in prototypes // add a 'contains' method to all String objects String.prototype.contains = function(text) { return this.indexOf(text) >= 0; }; ANY prototype can be modified, including existing types  many JS add-on libraries do this to augment the language  not quite the same as adding something to a single object Exercise: Add a reverse method to all strings. Exercise: Add a shuffle method to all arrays.

16 Pseudo class-based-inheritance function SuperClassName(parameters) {... } function SubClassName(parameters) {... } SubClassName.prototype = // connect them new SuperClassName(parameters);  to make a "subclass", tell its constructor to use an object of a "superclass" as its prototype  why not just write it this way? SubClassName.prototype = SuperClassName.prototype;

17 Pseudo-inheritance example // Constructor for Point3D "subclass" function Point3D(x, y, z) { this.x = x; this.y = y; this.z = z; } // set it to be a "subclass" of Point Point3D.prototype = new Point(0, 0); // override distanceFromOrigin method to be 3D Point3D.prototype.distanceFromOrigin = function() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); };

18 Problems with pseudo-inheritance there no equivalent of the super keyword  no easy way to call the superclass's constructor no built-in way to call an overridden superclass method  have to write it manually, e.g. var d = Point.prototype. distanceFromOrigin.apply(this); solution: many JS libraries add class creation syntax, e.g. Class.create(name, superclass,...)

19 The instanceof keyword expr instanceof ConstructorFunction returns true if the given object was constructed by the given constructor, or is in the object's prototype chain > var p = new Point(3, -4); > var p3d = new Point3D(3, -4, 5); > p instanceof Point true > p3d instanceof Point3D true > p3d instanceof Point true > "hello" instanceof Point || {} instanceof Point false

20 Another type test:.constructor > var p1 = new Point(3, -4); > p1.constructor function Point(xValue, yValue) {... } > var o = {}; > o.constructor function Object() {[native code for Object.Object]} every object has a constructor property that refers to the function used to construct it (with new )  if the object was created without a constructor using {}, its.constructor property refers to the Object() function  constructor can be changed; instanceof will still work

21 The base2 library load("base2.js"); // var Animal = Base.extend({ constructor: function(name) { this.name = name; }, name: "", eat: function() { this.say("Yum!"); }, say: function(message) { print(this.name + ": " + message); } });  intended to make inheritance/subtyping easier  all classes extend a common constructor called Base

22 Java within JavaScript the Rhino VM is written in Java  it implements a layer of JavaScript on top of Java Rhino lets you use Java classes in JavaScript  combine Java's rich class library with JavaScript's dynamism and simpler syntax current trend: languages that on top of the JVM  Clojure: a Lisp dialect  Scala: an ML-like functional language  Groovy: a scripting language  JVM adaptations: JRuby, Jython, Erjang, JScheme,...

23 Using Java classes in Rhino importPackage(Packages.package); importClass(Packages.package); var name = new JavaClassName(params); Example: > importPackage(Packages.java.util); > var s = new TreeSet(); > s.addAll(Arrays.asList([2,7,1,2,4,1,2,4])); > s [1.0, 2.0, 4.0, 7.0]

24 Accessing class properties JavaClassName.property JavaClassName["property"] Example: > var console = new Scanner(System.in); js: " ", line 44: missing name after. operator js: var console = new Scanner(System.in); js: ^ > var console = new Scanner(System["in"]);

25 Some Java ↔ JS quirks JS Number s are sometimes double s when used in Java > Arrays.asList([1, 2, 3]) [1.0, 2.0, 3.0] to force usage of int, use Integer objects > var list = new ArrayList(); > list.add(1); > list.add(new Integer(2)); > list [1.0, 2] char, long, short, byte are treated as Numbers in JS > var s = new java.lang.String("hello"); > s.charAt(0) 104

26 More Java ↔ JS quirks sometimes JS → Java can't tell what type to use: > var a = [4, 1, 7, 2]; > Arrays.sort(a); The choice of Java constructor sort matching JavaScript argument types (object) is ambiguous; candidate constructors are: void sort(java.lang.Object[]) void sort(long[]) void sort(int[])... Java collections/arrays DO have bounds checking > var list = new ArrayList(); > list.get(7); java.lang.IndexOutOfBoundsException: Index:7, Size:0

27 Implementing and extending new InterfaceOrSubclass(object) // or, new JavaAdapter(Packages.superclass, interface1,..., interfaceN, object) Example: > var o = { compare: function(s1, s2) { return s1.length() - s2.length(); }}; > var comp = new Comparator(o); > var set = new TreeSet(comp); > set.add("goodbye"); > set.add("what"); > set.add("bye"); > set.add("hello"); > set [bye, what, hello, goodbye]

28 Other direction: JS within Java Java 1.6 adds javax.script package to run JS code: import java.io.*; import javax.script.*; public class RunJS { public static void main(String[] args) throws Throwable { ScriptEngine engine = new ScriptEngineManager(). getEngineByName("javascript"); for (String arg : args) { engine.eval(new FileReader(arg)); }