CS61B L06 Control Structures (1)Garcia / Yelick Fall 2003 © UCB 2003-09-15  Dan Garcia (www.cs.berkeley.edu/~ddgarcia) Kathy Yelick  (www.cs.berkeley.edu/~yelick)

Slides:



Advertisements
Similar presentations
Classes And Objects II. Recall the LightSwitch Class class LightSwitch { boolean on = true; boolean isOn() { return on; } void switch() { on = !on; }
Advertisements

Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects:
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Written by: Dr. JJ Shepherd
TOPIC 12 CREATING CLASSES PART 1 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson,
Data Abstraction II SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
Defining classes and methods Recitation – 09/(25,26)/2008 CS 180 Department of Computer Science, Purdue University.
Road Map Introduction to object oriented programming. Classes
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Abstract Classes and Interfaces
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Inheritance. Recall the plant that we defined earlier… class Plant { public: Plant( double theHeight ) : hasLeaves( true ), height (theHeight) { } Plant(
Chapter 3 Introduction to Collections – Stacks Modified
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Cs205: engineering software university of virginia fall 2006 Data Abstraction David Evans
CSC 212 Object-Oriented Programming and Java Part 1.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Computer Science and Engineering College of Engineering The Ohio State University Interfaces The credit for these slides goes to Professor Paul Sivilotti.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
Lecture 2: Classes and Objects, using Scanner and String.
CS61B L03 Building Objects (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Question of the Day  On a game show you’re given the choice of three doors: Behind one door is a car; behind the others, goats. After you pick a door,
CS61B L02 Using Objects (1)Garcia / Yelick Fall 2003 © UCB Kathy Yelick Handout for today: These lecture notes Computer Science 61B Lecture 2 – Using Objects.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
CS61B L12 Arrays and Implementing Enumerations (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick.
CS61B L08 Vectors, Enumeration & Project 1 (1)Garcia / Yelick Fall 2003 © UCB Never forget…
Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???
CSC1401 Classes - 1. Learning Goals Computing concepts Identifying objects and classes Declaring a class Declaring fields Default field values.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Types in programming languages1 What are types, and why do we need them?
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CS61B L11 Testing & Static (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
Data Abstractions EECE 310: Software Engineering.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 1: Introduction Data.
CS61B L07 Specification and Documentation (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
CS61B L10 Exceptions (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
Written by: Dr. JJ Shepherd
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
CS61B L13 Lists (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 5: Implementing Data Abstractions.
Reasoning and Design (and Assertions). How to Design Your Code The hard way: Just start coding. When something doesn’t work, code some more! The easier.
Problem of the Day  Why are manhole covers round?
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Lecture 4: Data Abstraction CS201j: Engineering Software
Java Programming Language
Review for Midterm 3.
Presentation transcript:

CS61B L06 Control Structures (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  ( inst.eecs.berkeley.edu/~cs61b/ 1 Handout: notes Computer Science 61B Data Structures and Advanced Programming Lecture 9 – Arrays and Invariants

CS61B L06 Control Structures (2)Garcia / Yelick Fall 2003 © UCB Where is Dan? Hurricane Isabel No office hours this week for Dan

CS61B L06 Control Structures (3)Garcia / Yelick Fall 2003 © UCB Vectors Review Vectors are objects that look like: The boxes can only hold references to objects –Not 1, 2.3, or other basic types. –Can mix objects: 1 Vector may contain Accounts, Motes, Vectors… Elements are numbered from 0 to size-1 Vectors are a mutable type –The objects can be replaced by other objects –Vectors can grow and shrink In Java library: import java.util.*;

CS61B L06 Control Structures (4)Garcia / Yelick Fall 2003 © UCB Object: The Universal Parent Java is an object-oriented language –One type inherits from another –You can use the subtype (child type) anywhere the supertype (parent type) is expected –Given a Vector v of >=2 elements: »Object obj = v.get(1); is legal »obj.intValue() is a compile-time error »(Integer obj).intValue() compiles, but is a runtime error if obj is not really an Integer »obj.toString() is always legal … more about this in a couple of weeks Object Account Vector array Integer obj ?

CS61B L06 Control Structures (5)Garcia / Yelick Fall 2003 © UCB Arrays are Similar Arrays are objects that look like: The boxes can hold references to –Objects or primitives, e.g., 1, 2.3 –But type of all primitive elements must be the same The boxes are numbered from 0 to size-1 Arrays are a mutable type –The elements can be replaced by other elements –But, they cannot grow and shrink Arrays are built into the Java language, not in the library, so no need to “import”

CS61B L06 Control Structures (6)Garcia / Yelick Fall 2003 © UCB Creating Arrays Declaration uses [] and element type: int [] intArr; can contain int values Account [] acctArr; can contain “Account” refs, or nulls Object [] objArr; can contain any Object ref, or nulls To create array object, use new intArr = new int[3]; acctArr = new Account[2]; objArr = new Object[1]; intArr acctArr01 objArr

CS61B L06 Control Structures (7)Garcia / Yelick Fall 2003 © UCB Using Arrays One can get/set elements using [] syntax: intArr[0] = 0; // don’t rely on defaults for now intArr[1] = 2; intArr[2] = 4; int y = intArr[1]; As with Vectors, need to have the object before using it: int [] a2; a2[0] = 2; // error – no array allocated yet Shorthand for initialization (only with decl): int [] a3 = {2, 4, 6}; a2 = {1, 2, 3}; // not allowed

CS61B L06 Control Structures (8)Garcia / Yelick Fall 2003 © UCB Types and Arrays Arrays element types must match declaration: intArr[1] = new Account(100); // compiler error intArr[1] = new Integer(1); // compiler error But you can have an array of Objects Object [] objArr = {new Account(100), new Integer(1)}; objArr[0] = new Integer(2); objArr01 myBalance x

CS61B L06 Control Structures (9)Garcia / Yelick Fall 2003 © UCB Multidimensional Arrays A multidimensional array in Java is an array of arrays: int [][] x = new int [3][2]; int [][] y = new int[2][]; y[0] = new int[2]; y[1] = new int[1] y[1][0] = 3; x y 1 0 3

CS61B L06 Control Structures (10)Garcia / Yelick Fall 2003 © UCB “Growing” and “Shrinking” Arrays Once an array is created, its size does not change However, we can copy smaller ones to larger ones int [] myArr = {3, 6, 5}; //... use myArr, but what if it’s now too small intArr tmpArr201 x myArr int [] tmpArr = new int [2*myArr.length + 1]; for (int k = 0; k < myArr.length; k++) { tmpArr[k] = myArr[k]; } // rest of tmpArr uninitialized (default 0) myArr = tmpArr; See also System.arrayCopy

CS61B L06 Control Structures (11)Garcia / Yelick Fall 2003 © UCB An Aside: Understanding main Recall the signature of the main method: public static void main (String [] args) This says main takes an array of Strings E.g., public static void main (String [] args) { System.out.println(args[0]); int i = Integer.parseInt(args[1]); System.out.println(“args[1] = “ + i); } As with reading from System.in, more error checking should be used.

CS61B L06 Control Structures (12)Garcia / Yelick Fall 2003 © UCB Administrivia Reading assignments –For Wednesday : Liskov 10 and –For Friday: ADW Chapter 8 CSUA Help session for advanced Unix postponed. HW #3 due 11:59pm –Correction in hw3.html (api was OK). »See hw3/Errata.txt (similarly for proj1) Quiz in 1 week1: Monday, –In-class, open book/notes, last2 slides contains topics Project #1 handed out on Friday, due ~2 wks

CS61B L06 Control Structures (13)Garcia / Yelick Fall 2003 © UCB Designing Data Abstractions Major questions to answer: –How does the abstract object behave to the outside world? (the specification) –How do we represent the data internally in our implementation? (the implementation) –What properties do we enforce on the state of our internal representation? (representation invariant) –How does a concrete value map to an abstract one? (abstraction function) Project 1: design a Landlord class –Specification: given »Do not add public methods that your tester tests –Implementation: Use a Vector of plots »Options: store “rented” or “vacant”, sorted?

CS61B L06 Control Structures (14)Garcia / Yelick Fall 2003 © UCB Representation Invariant Representation invariant: a property of the concrete (implementation) object that holds on entry/exit of all methods in the class –What values may private instance variables have? –Methods assume the invariant holds on entry –Methods that change the instance variables must ensure the invariant still holds when they exit Why use a representation invariant? –Allows us to reason about the correctness of each method in isolation –May make some method faster or easier to write –Self-discipline: you make up and enforce the rules

CS61B L06 Control Structures (15)Garcia / Yelick Fall 2003 © UCB Representation Invariant - Fraction Recall: Fractions are immutable (in the abstract), and toString() shows in reduced form Possible invariants for the Fraction class: –weak invariant: myDenom != 0 »toString() can’t assume anything, always must reduce –weak invariant with benevolent side-effects »Same as above, except toString() replaces instance variables with reduced form after calling gcd() »“Benevolent” because it does a good thing Future calls to gcd will be very fast The side effect is not user-visible –strong invariant: always store in reduced form »myDenom != 0 AND gcd(myNumer, myDenom) == 1

CS61B L06 Control Structures (16)Garcia / Yelick Fall 2003 © UCB Abstraction Function Expresses the “meaning” of the values in the object’s instance variables as a whole –Tells us how interpret the concrete state of the instance variables to recover the abstract object they represent This Fraction object represents the abstract rational number ½ : So does this one: Abstraction functions are often many-to-one –Several concrete states may represent the same abstract object The abstraction function for Fraction is division: –AF(c) = c.myNumer / c.myDenom Do 3 different implementation have different AFs? 1 myNumer 2 myDenom 4 myNumer 8 myDenom 1212

CS61B L06 Control Structures (17)Garcia / Yelick Fall 2003 © UCB Representation Invariant – repOk() Often a good idea to include a “self-test” method that checks whether the invariant holds: true if the object representation * is in a legal state satisfying the invariant, * otherwise return false */ public boolean repOk() { return ((myDenominator != 0) && (gcd(myNumer, myDenom) == 1)); } When to call repOk? –When invariant may be broken: at the end of all constructors and methods that change the object (mutators) as a self-diagnostic –Also on entry to methods that rely on the invariant Since check may be costly, may turn it off in “released” version of code using: assert repOk(); // more in next lecture

CS61B L06 Control Structures (18)Garcia / Yelick Fall 2003 © UCB Representation Exposure A well-designed data abstraction can guarantee its representation invariants –Variables are usually private to ensure invariants User may still be able to violate the invariants –Representation exposure: giving the user of an abstract data type access to the internals, allowing them to violate representation invariants If all fields are private, how does this happen? –Taking mutable objects from user and putting them into the internal state –Returning mutable parts of the state

CS61B L06 Control Structures (19)Garcia / Yelick Fall 2003 © UCB PRS Question The following code for proj1 has as an invariant: Plots in myPlot (which store the beginning/size) do not overlap How many “lines” need to be changed to ensure the user cannot break the invariant? 1: none 2: 2 3: 2&3 4: 2&4 5: 3&4 6: 2-4 7: 2-5 1)public class Landlord { 2) public Vector myPlots; 3) Landlord (Vector initP) { myPlots = initP; } 4) Vector getPlots () { return myPlots; } 5) Plot plotAt(int i) { return myPlots.get(i); } 6) }

CS61B L06 Control Structures (20)Garcia / Yelick Fall 2003 © UCB Data Abstraction Summary Data Abstraction is a powerful programming tool –Provide an abstract data object and a set of useful operations to the outside world –Hide the implementation details Representation Invariant –Rules about how the internal variables are managed –Include a repOk() method that checks whether any of the rules have been violated at run time Abstraction Function –Describes the mapping from your concrete representation using instance variables to the abstract object your class represents Benevolent side effects –Modifications of internal state that are not externally visible

CS61B L06 Control Structures (21)Garcia / Yelick Fall 2003 © UCB Announcements - Quiz Open book/open notes Topics: –Basic Java 1.Writing and using classes and methods 2.Conditionals, loops, and recursion 3.Parameter passing 4.Primitive values vs. objects (and references to them) 5.public and private 6.static and non-static 7.Exceptions 8.Vectors/Enumerations Note: repOK and loop invariants will not be on this modifies”) –Testing

CS61B L06 Control Structures (22)Garcia / Yelick Fall 2003 © UCB Announcements - Quiz Review session –Tuesday or Wednesday evening: watch newsgroup for details Exam questions often use examples you have seen. –We will include the code, but you will have time problems if you’re seeing it for the first time. Examples from labs and homeworks (through lab 4 and homework 3): –Account –Fraction –StringFormat (hw) –StringCheck (lab) –IslamicDate –Vector and Enumeration (lab) Solutions for labs and homeworks online