Manu Kumar sneaker@stanford.edu CS193J: Programming in Java Summer Quarter 2003 Lecture 3 Collections and More OOP Manu Kumar sneaker@stanford.edu Thursday,

Slides:



Advertisements
Similar presentations
Java Review Interface, Casting, Generics, Iterator.
Advertisements

June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 6 Object Oriented Programming in Java Language Basics Objects.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10 Classes Continued
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Lists and the Collection Interface Review inheritance & collections.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Data structures Abstract data types Java classes for Data structures and ADTs.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
ISBN Object-Oriented Programming Chapter Chapter
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Introduction to Object-Oriented Programming Lesson 2.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
EKT472: Object Oriented Programming
Using the Java Collection Libraries COMP 103 # T2
Modern Programming Tools And Techniques-I
Inheritance ITI1121 Nour El Kadri.
Lecture 12 Inheritance.
Chapter 11 Inheritance and Polymorphism
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Inheritance and Polymorphism
Methods Attributes Method Modifiers ‘static’
Object Oriented Programming in Java
Implementing ArrayList Part 1
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Comp 249 Programming Methodology
Lecture 23 Polymorphism Richard Gesick.
Chapter 9 Inheritance and Polymorphism
Inheritance Basics Programming with Inheritance
Java Programming Language
Polymorphism.
Week 6 Object-Oriented Programming (2): Polymorphism
Computer Programming with JAVA
Java – Inheritance.
Inheritance Inheritance is a fundamental Object Oriented concept
Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
ArrayLists 22-Feb-19.
Based on slides by Alyssa Harding & Marty Stepp
Polymorphism 2019/4/29.
Web Design & Development Lecture 6
CSE 143 Lecture 21 Advanced List Implementation
Java String Class String is a class
Classes and Objects Object Creation
C++ Object Oriented 1.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Manu Kumar sneaker@stanford.edu CS193J: Programming in Java Summer Quarter 2003 Lecture 3 Collections and More OOP Manu Kumar sneaker@stanford.edu Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Recap Last time (a somewhat jumpy introduction to…) To Dos OOP in Java (Student Example) Explore more Java features Primitives Arrays Multi-Dimensional Arrays String Class StringBuffer Class Static keyword OOP Design Encapsulation Interface vs. Implementation Client Oriented Design To Dos HW1: Pencil Me In Due before midnight Wednesday July 9th, 2003 Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Handouts 3 Handouts for today! Next time #8: Collections #9: OOP2 - Inheritance #10: OOP3 – Abstract Superclasses Next time Complete OOP Probably won’t get to all of it today Start Drawing/GUI Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

You will have all you need for HW#1 Today Java Collections ArrayList example OOP Inheritance Grad example Abstract Superclasses Account example Java Interfaces You will have all you need for HW#1 By the end of today’s lecture. Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Collections (Handout #8) Built-in support for collections Similar to STL in C++ Collection type Sequence/Set Example ArrayList Map type Hashtable/dictionary Example HashMap Collections store pointers to objects! Use inheritance and interfaces Read http://java.sun.com/docs/books/tutorial/collections Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Collection Design All classes implement a similar interface add(), size(), iterator()… Easy learning curve for using Collections Possible to swap out the underlying implementation without significant code change Implemented as pointer to Object Similar to using a void * in C Require a cast back to the actual type Example String element = (String)arraylist.get(i) Java checks all casts at run-time Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Collection Messages Basic messages constructor() size() boolean add() Creates a collection with no elements size() Number of elements in the collection boolean add() Add a new pointer/element at the end of the collection Returns true is the collection is modified. iterator() Returns an Iterator Object Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Additional Collection Messages Utilities Additional useful methods boolean isEmpty() boolean contains(Object o) Iterative search, uses equals() boolean remove(Object o) Iterative remove(), uses equals() Boolean addAll(Collection c) Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Used to iterate through a collection Iterators Used to iterate through a collection Abstracts away the underlying details of the implementation Iterating through an array is the same as a binary tree Responds to hasNext() - Returns true if more elements next() - Returns the next element remove() - removes element returned by previous next() call. Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Working with Iterators Not valid to modify a collection directly while an iterator is being used! Should not call collection.add() or collection.remove() OK to modify the collection using the iterator itself iterator.remove() Why? Motivation for concurrency issues later in the course Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

ArrayList Most useful collection Replaces the “Vector” class Can grow over time Methods add() int size() Object get(int index) Index is from 0 to size() -1 Must cast to appropriate type when used. iterator() We’ll see an ezample! Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

ArrayList Demo: constructor import java.util.*; /* The ArrayList is replaces the old Vector class. ArrayList implements the Collection interface, and also the more powerful List interface features as well. Main methods:add(), size(), get(i), iterator() See the "Collection" and "List" interfaces. */ public static void demoArrayList() { ArrayList strings = new ArrayList(); … Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

ArrayList Demo: adding/size // add things... for (int i= 0; i<10; i++) { // Make a String object out of the int String numString = Integer.toString(i); strings.add(numString); // add pointer to collection } // access the length System.out.println("size:" + strings.size()); Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

ArrayList Demo: looping // ArrayList supports a for-loop access style... // (the more general Collection does not support this) for (int i=0; i<strings.size(); i++) { String string = (String) strings.get(i); // Note: cast the pointer to its actual class System.out.println(string); } Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

ArrayList: iterating // ArrayList also supports the "iterator" style... Iterator it = strings.iterator(); while (it.hasNext()) { String string = (String) it.next(); // get and cast pointer System.out.println(string); } // Calling toString() System.out.println("to string:" + strings.toString()); Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

ArrayList Demo: removing // Iterate through and remove elements // get a new iterator (at the beginning again) it = strings.iterator(); while (it.hasNext()) { it.next(); // get pointer to elem it.remove(); // remove the above elem } System.out.println("size:" + strings.size()); Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

ArrayList Demo: output size:10 1 2 3 4 5 6 7 8 9 to string:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] size:0 */ Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

OOP – Inheritance (Handout #9) OOP so far Modularity Encapsulation Today Open Pandora’s box Inheritance Abstract Super Classes Warning True good uses of inheritance are rare Use it only where it is really appropriate. Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Classes are arranged in a tree hierarchy A class’ “superclass” is the class above it in the hierarchy Classes below is are “subclasses” Classes have all the properties of their superclasses General – towards the root (top) More specific – towards the leaves (down) NB: In Computer Science trees grow upside down! Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Example Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Inheritance The process by which a class inherits the properties of its superclasses Methods Instance variables Message-Method resolution revisited Receive message, check for method in class If found, execute Check for method in superclass If found, execute, if not, repeat this procedure Basic idea: Travel up the tree. Result: A class automatically responds to all the messages and has all the storage of superclasses Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

“Overriding” When an object receives a message It checks it own methods first Then check the superclass’ methods The first method in the hierarchy takes precedence We can add a method with the same name as in the superclass in the class The code of the superclass will not be executed It is effectively “overridden” i.e. intercepted In C++ runtime overriding is an option invoked by the “virtual” keyword. Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Do not be intimidated by the big word Polymorphism Do not be intimidated by the big word It’s a simple concept Basic idea: “it does the right thing” An Object always knows its true class at runtime The MOST specific method found for the object is executed. Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Polymorphism example Shape is a superclass of Rectangle Code: Shape.drawSelf() and Rectangle.drawSelf() Code: Shape s; Rectangle r = new Rectangle(); s = r; s.drawSelf() Which method will get execute? Shape.drawSelf() or Rectangle.drawSelf()? Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

OOP Glossary OOP Class Hierarchy Superclass Subclass Inheritance Overriding isA the subclass is a instance of the superclass Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Hierarchy of all the animals Options Horse/Zebra Example Hierarchy of all the animals Need to add in Zebra Options Define zebra from scratch Bad idea – mutlitple copies of code. Locate the Horse class and subclass it to create the Zebra class Zebra will inherit most of the characteristics of a horse Override or add additional features as needed Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Grad Example Add Grad as an extension to the Student class from previous lecture. yearsOnThesis – a count of the number of years worked on the thesis getStress() – overridden to be different 2 * the Student stress + yearsOnThesis Grad is everything that a student is Has additional or some different properties Grad is “more specific” Grad (subclass) has more properties, and is more constrained that Student (superclass) Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Student/Grad Design Diagram Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Simple Inheritance Client Code Instantiation Student s = new Student(10); Grad g = new Grad(10, 2); // ctor takes units and yot Usage (normal) s.getStress(); // (100) goes to Student.getStress() Usage (inheritance) g.getUnits(); // (10) goes to Student.getUnits() Usage (overriding) g.getStress(); // (202) goes to Grad.getStress() Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Clarifications and Reminders An Object never forgets it’s Class The receiver always knows it’s most specific class Student s; in the face of inheritance No: “s points to a Student object” Yes: “s points to an object that responds to all the messages that Students respond to” Yes: “s points to a Student, or a subclass of Student” Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

OOP Pointer Substitution A subclass isA superclass A subclass object can be used when you are expecting a superclass The subclass has everything the superclass has and more (not less!) Compile time error checking Compiler will only allow code in which the receiver respond to the given message Implemented as loose checking since sometimes the exact class is not known (Student or Grad both work) Run time error checking More strict. Receiver knows exactly which class it is. Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Pointer Substitution Example A pointer to a Grad object be assigned to Student pointer. Student s = new Student(10); Grad g = new Grad(10,2); s = g; // ok -- subclass may be used in place of superclass The reverse is not allowed however g = s; // NO, does not compile Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Example of method calls Student s = new Student(10); Grad g = new Grad(10, 2); s = g; // ok s.getStress(); // (202) ok -- goes to Grad.getStress() (overriding) s.getUnits(); // (10) ok -- goes to Student.getUnits (inheritance) s.getYearsOnThesis(); // NO -- does not compile (s is compile time type Student) Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Downcast Sometimes the programmer can give the compiler more information Done by providing a more specific cast around a less specific object ((Grad)s).getYearsOnThesis(); Downcast Makes a more specific claim All casts are checked at runtime Will throw ClassCastException if there is a problem In C, the program would crash unpredictably In general: Downcasting is bad style! Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Student/Grad Memory Layout Implementation detail In memory, instance variables of the subclass are layers on top of the instance variables of the subclass Result A pointer to the base instance of the subclass can be treated as if it were a superclass object A Grad object looks like a Student object Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Inheritance Client Code Student s = new Student(10); Grad g = new Grad(15, 2); Student x = null; System.out.println("s " + s.getStress()); System.out.println("g " + g.getStress()); // Note how g responds to everything s responds to // with a combination of inheritance and overriding... g.dropClass(3); /* OUTPUT... s 100 g 302 g 242 */ Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Inheritance Client Code // s.getYearsOnThesis(); // NO does not compile g.getYearsOnThesis(); // ok // Substitution rule -- subclass may play the role of superclass x = g; // ok // At runtime, this goes to Grad.getStress() // Point: message/method resolution uses the RT class of the receiver, // not the CT class in the source code. // This is essentially the objects-know-their-class rule at work. x.getStress(); // g = x; // NO -- does not compile, // substitution does not work that direction // x.getYearsOnThesis(); // NO, does not compile ((Grad)x).getYearsOnThesis(); // insert downcast // Ok, so long as x really does point to a Grad at runtime Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

isIrate() example isIrate() method in the Student Class Returns true is stress > 100 In the Student Class: public boolean isIrate() { return (getStress() > 100); } What happens with the following client code: Student s = new Student(...); Grad g = new Grad(....); s.isIrate(); g.isIrate(); Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

How g.isIrate() works… g known that is a Grad Object It looks for an isIrate method Not found, so climbs up the tree to the Student class Method found in Student class isIrate() has a call to getStress() Since g knows it is a Grad Object (and it doesn’t forget this!) it will call the Grad.getStress() Grad.getStress() in turn calls Student.getStress()!! We will see this when we examine the implementation code! Bottom line: it does the right thing! Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

“Pop-Down” rule The reciever knows it’s class The flow of control jumps around different classes No matter where there code is executing the receiver knows its class and does the messagemethod mapping correctly for each message! Example Receiver is the subclass (Grad), executing a method in the superclass(Student) A message send that Grad overrides will “pop-down” to the Grad definition as in the case of getStress() ) Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

super.getStress() The “super” keyword is used in methods and constructors to refer to code in the superclass Calling super.getStress() in the Grad class would execute the code for getStress() in the Student Class Think of super as a directive to the messagemethod resolution process. Start searching one level higher. Allows the subclass to not have to rewrite the code Re-use the code in the superclass and add to the functionality Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Continue on Lecture 4… Continued on Lecture 4… Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar

Assigned Work Reminder: Summary Today Java Collections ArrayList example OOP Inheritance Grad example Assigned Work Reminder: HW #1: Pencil Me In Due before midnight Wednesday, July 9th, 2003 Thursday, June 26th, 2003 Copyright © 2003, Manu Kumar