Interacting Classes Lecture #6 CMPSCI 121, Spring 2005 Introduction to Problem Solving with Computers Prof. McCallum No quiz today. It will again be in.

Slides:



Advertisements
Similar presentations
Chapter 5 Implementing a simple class. This chapter discusses n Implementing class definitions. n How to store data in an object and how to write method.
Advertisements

Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Lecture 2: Object Oriented Programming I
Introduction to Programming with Java, for Beginners “Has a” Relationship.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Chapter 41 Defining Classes and Methods Chapter 4.
Introduction to Programming with Java, for Beginners
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Introduction to Primitives. Overview Today we will discuss: –The eight primitive types, especially int and double –Declaring the types of variables –Operations.
Implications of Substitution Fall 2005 OOPD John Anthony.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 5a: Input and.
CSE 115 Week 3 January 28 – February 1, Monday Announcements Software Installation Fest: 2/5 and 2/6 4pm – 7pm in Baldy 21 Software Installation.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
Guide To UNIX Using Linux Third Edition
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
MIT AITI 2003 Lecture 7 Class and Object - Part I.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Writing Classes (Chapter 4)
CSE 1301 Lecture 11 Object Oriented Programming Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
CS 121 – Intro to Programming:Java - Lecture 7 Announcements A new Owl assignment is available. Programming assignment 4 is due on Thursday - hand in on.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Fall 2015CISC124 - Prof. McLeod1 CISC124 Have you filled out the lab section survey? (As of last night 54 left to fill out the survey.) TA names have been.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Chapter 9 Putting together a complete system. This chapter discusses n Designing a complete system. n Overview of the design and implementation process.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Today… “Hello World” ritual. Brief History of Java & How Java Works. Introduction to Java class structure. But first, next slide shows Java is No. 1 programming.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Week 12 - Wednesday.  What did we talk about last time?  Hunters and prey.
Week 12 - Monday.  What did we talk about last time?  Defining classes  Class practice  Lab 11.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Java Classes Introduction. Contents Introduction Objects and Classes Using the Methods in a Java Class – References and Aliases Defining a Java Class.
Session 7 More Implications of Inheritance & Chapter 5: Ball World Example.
Lecture 11 Instructor: Craig Duckett Instance Variables.
Information and Computer Sciences University of Hawaii, Manoa
Lecture 10: More on Methods and Scope
Lecture 6 C++ Programming
CS Week 6 Jim Williams, PhD.
Introduction to the C Language
Variables, Types, Operations on Numbers
Implementing a simple class
Object Oriented Programming Review
Introduction to Data Structure
CS Week 2 Jim Williams, PhD.
Classes and Objects Object Creation
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Interacting Classes Lecture #6 CMPSCI 121, Spring 2005 Introduction to Problem Solving with Computers Prof. McCallum No quiz today. It will again be in lab on Thursday. (Read Chapter 3). OWL Written Exercise is due Thursday 9am. Programming Assignment #5 was due this morning. Today’s music: Aaron Copland, Hungarian Rhapsody #2

1 Midterm Results Finished grading same day you took it; back to you in labs. On the whole you did very well! Congratulations! You have learned a lot! Average: 80 (+11 EC), Median: 81, Min: 27, Max: 100 (x5) Midterm roughly: A (#46) B (#54) B (#23) C (#22) D (#15) F 49-0 (#11) Subject to change!

2 Dropping? I hope not, and that you’ll stick with it! But if you can’t: Last day (without the need to petition the Dean) is Monday the 30th Can go to Pauline at the front desk in the CS main office.

3 Midterm You are turning into real programmers now. In future quizzes and exams there will be more questions like this:

4 Pace of the course Steep and fast in beginning Slowed down before midterm It’s been 3 weeks since we’ve had a new concept in this course! Now after the midterm, steep and fast again Next three weeks are crucial Work hard. Don’t fall behind. Read the text book!

5 Primitive and Reference Types We’ve seen Java’s 8 primitive types: int, double, boolean, char (also byte, short, long, float) Java also has reference types, for objects Examples of reference variables: String name; Counter c1; They are called references because they refer to a memory location where the object lives

6 Memory: Stack and Heap When we use the DrJava interactions pane, and when we run a standalone Java program or applet, memory is allocated for variables and objects Understanding how this memory is managed helps us understand how Java works The JVM uses a stack and a heap. The stack is used to store: Variables we create in the DrJava interactions pane A “stack frame” for each active method call (we’ll discuss this later in the course) The heap is used to store objects.

7 How the Stack Grows DrJava InteractionsStack > int x; > x = 5; > double min = 0.5; > boolean done = false;

8 How the Heap Grows DrJava InteractionsStack and Heap > int x = 99; > Counter c1; > c1 null > c1 = new Counter(); > c1 > c1.incrementCount(); > Counter c2 = new Counter(); > c2

9 Value of a Reference Variable The value of are reference variable is either null or a “heap address” Example: > Counter c1; > c1 null > c1 = new Counter(); > c1 e05ad6 is a hexadecimal (base 16) number We don’t have to (and can’t) deal with these hex numbers directly

10 “Has a” Relationship Example: An object of type A has an instance variable which is an object whose type is B. (A “has a” B.) We will create a DormRoom object, and a Freshman object whose room is that DormRoom UML diagrams that show instance variables and methods:

11 DormRoom: Code and UML > DormRoom room = new DormRoom(208, "Hill"); > room.getLocation() "208 Hill" public class DormRoom{ private int num; private String bldgName; public DormRoom(int n, String b){ num = n; bldgName = b; } public String getLocation(){ return num + " " + bldgName; } }

12 A DormRoom on the Heap > DormRoom room = new DormRoom(208, "Hill"); > room.getLocation() "208 Hill"

13 Freshman Code and UML > DormRoom room = new DormRoom(208, "Hill"); > Freshman f = new Freshman("jo", room); > f.getName() "jo" > f.getRoom().getLocation() "208 Hill" public class Freshman{ private String name; private DormRoom room; public Freshman(String n, DormRoom r){ name = n; room = r; } public String getName(){ return name;} public DormRoom getRoom(){ return room;} }

14 A Freshman on the Heap :) > DormRoom room = new DormRoom(208, "Hill"); > Freshman f = new Freshman("jo", room); > f.getName() "jo" > f.getRoom().getLocation() "208 Hill"

15 Fred Brooks Computer Scientist of the Week Ph.D. Harvard, “Applied Math”, 1596 Managed development of OS/390 at IBM. Mythical Man-month “Assigning more programmers to a project running behind schedule, could actually make it even more late” No Silver Bullet “No more technologies or practices that will create a 10-fold improvement in software engineering productivity over 10 years” Winner of Turing Award in 1999.

16 Another example... A point on the plane is given by its coordinates x, y in a fixed frame of reference public class Point { private double x, y; Point(double anX, double aY) { x = anX; y = aY; } public double getX() { return x; } public double getY() { return y; } } Add a move(double dx, double dy) method to this class.

17 Moving a point Add a moving behavior to Point … with a command public class Point { private double x; private double y; … public void move(double dx, double dy) { x = x + dx; y = y + dy; }

18 Moving points

19 Building on Point A circle is defined by its center (a point) and its radius (a double) public class Circle { private Point center; private double radius; public Circle(Point aCenter, double aRadius) { center = aCenter; radius = aRadius; } public Point getCenter() { return center; } public double getRadius() { return radius; } }

20 Complex objects Point p = new Point(1, 2); Circle c = new Circle(p,.5); c.getCenter().getX()  1 ??

21 Moving a Circle public class Circle { private Point center; private double radius; … public void move(double dx, double dy) { center.move(dx, dy); } To move a circle move its center

22 Behind the scenes Objects are implemented as chunks of memory Object variables contain the addresses of the chunks, not the chunks themselves That is, object variables hold references to objects

23 The reference to nowhere Uninitialized object type variables contain null It's a value in all object types But it refers to no object Often used to indicate missing or optional data Point p = null; Circle c = new Circle(p,.5); c.move(1,1); java.lang.NullPointerException: at Circle.move(Circle.java:33) …

24 Resolving method names The name is resolved by the class of the object Point p = new Point(1,1); Circle c = new Circle(1,1,.5); p.move(.5,1).getX()  1.5 c.move(.5,1).getCenter().getX()  1.5

25 Aliases Several variables can refer to the same object—aliasing Point p = new Point(1,1); Point p1 = p; p.move(.5, 1); p.getX()  1.5 p1.move(2, 0); p1.getY()  3.5

26 The dangers of aliasing… Point p = new Point(1,1); Circle small = new Circle(p,.5); Circle big = new Circle(p, 5); small.move(.5, 2); big.move(5, 20); small.getCenter().getX()  ? big.getCenter().getX()  ?

27 … illustrated

28 Designing with objects Complex problems involve multiple kinds of objects Stock market: stocks, orders, order books, trades,... Object responsibilities: Knowing facts: stock ticker symbol, order type (buy, sell,...), trade amount,... Doing actions: executing trade, clearing order, updating ask/bid price,...

29 Another example: A maze game Maze explorers (just one, representing the player, for now) move around interact with denizens Maze denizens interact with explorers Rooms Where explorers and denizens are located

30 Explorer knowledge Name: name Location in maze (room): location How much annoyance it can inflict: strength How much annoyance it can tolerate: tolerance

31 Responsibilities and commands Explorer can be told to... Move around: move (to a new location) Fight a denizen: poke (a denizen) Receive a poke from a denizen, decreasing tolerance: takeThat Denizen can be told to... Fight an explorer: poke (an explorer) Receive a poke from an explorer: takeThat

32 Interaction diagram

33 An explorer gets hit

34

35 Create and query an explorer public class Explorer { private String name; private Room location; private int strength; private int tolerance; public Explorer(String nm, Room loc, int str, int tol) { name = nm; location = loc; strength = str; tolerance = tol; } public String name() { return name; } public Room location() { return location; } public int strength() { return strength; } public int tolerance() { return tolerance; }... }

36 Command an explorer - fill in ??? public class Explorer { private String name; private Room location; private int strength; private int tolerance;... public void move(Room newRoom) { ????????????? } public void takeThat(int hitStrength) { ????????????? } public void poke(Denizen opponent) { opponent.takeThat(strength); }

37 Command an explorer public class Explorer { private String name; private Room location; private int strength; private int tolerance;... public void move(Room newRoom) { location = newRoom; } public void takeThat(int hitStrength) { tolerance -= hitStrength; } public void poke(Denizen opponent) { opponent.takeThat(strength); }

38 MazeWorld in action

39 A Movie with a Sequel

40 A complete system Model: represents the objects and relationships of interest characters, rooms,... in video game your bank account(s) Interface: allows a user (or another system) to interact with the model graphics, joystick commands ATM

41 Interactive system Controller Model View Interface Input Output input in Java is more complicated and will be discussed later

42 Reminder: points and circles Point constructor public Point(double x, double y) Point queries public double getX() public double getY() Circle constructor public Circle(Point center, double radius) Circle queries public Point getCenter() public double getRadius()

43 Setting up a view Define viewers for different classes of objects Point viewer PointViewer Constructor: public PointViewer(Point p) Viewing command: public void display() Circle viewer CircleViewer Constructor: public CircleViewer(Circle c) Viewing command: public void display() A viewer keeps a reference to its object If the object changes, the next display call shows the changed object

44 Displaying In a more “real” system, displaying might involve graphics, for example Here we use the simplest form of output The built-in System.out object provides a channel to the standard output device (the screen) Output command public void println(String s) Write a line with text s on the standard output device

45 Point viewer public class PointViewer { private Point point; public PointViewer(Point p) { point = p; } public void display() { System.out.println("A point at " + point.getX() + ", " + point.getY()); }

46 Circle viewer public class CircleViewer { private Circle circle; public CircleViewer(Circle c) { circle = c; } public void display() { System.out.println("A circle at " + circle.getCenter().getX() + ", " + circle.getCenter().getY() + " with radius " + circle.getRadius()); }

47 Getting it started We’ve been using DrJava to create objects and interact with them What if we want our Java code to work on its own? We need a stand-alone way of creating the appropriate objects and and making them work for us The main method: the Java virtual machine calls it to start the execution of a Java program

48 The main program public class PointCircleDisplay { public static void main(String[] args) { Point p = new Point(2, 3); PointViewer pv = new PointViewer(p); pv.display(); p.move(1, -1); pv.display(); Circle c = new Circle(p, 1); CircleViewer cv = new CircleViewer(c); cv.display(); p.move(.5,-2); cv.display(); }

50 Two roles for classes So far: classes as templates for objects instance variables: object data methods: object functionality But also: classes as containers for functionality and data that does not need multiple instances

51 What goes into a class Static: same independently of how they are accessed Variables: same value Methods: same computation Dynamic: different for different class instances Variables: different values Methods: computation may depend on instance variables

52 Putting it all together Using static and dynamic: numbered tickets public class Ticket { private static int issued; public static int getIssued(){ return issued; } private int number; public Ticket() { number = issued++; } public int getNumber() { return number; } static dynamic

53 Issuing tickets Ticket t1 = new Ticket(); t1.getNumber()  0 Ticket t2 = new Ticket(); t2.getNumber()  1 Ticket.getIssued()  2 The static variable issued tracks the total number of Ticket objects The instance (dynamic) variable number stores the number of a particular Ticket object

54 Classes as containers Container for a set of related static methods and variables To access non-private static members of class X variable: X.var method: X.meth(...)

55 Example: the Math class Defines common mathematical constants and functions Math.PI  Math.sin(Math.PI/2)  1.0 Math.log(Math.E)  1.0 Math.pow(2,3)  8.0 Math.pow(2, 0.5)  Math.sqrt(3*3 + 4*4)  5.0

56 Method Overloading There are in fact two max methods The appropriate one is chosen from the argument types Math.max(1, 2)  2 Math.max(1.0, 2.0)  2.0 static int max(int a, int b) static double max(double a, double b)

57 Named constants Name light values to isolate clients from specific values public class TrafficSignal { public static final int GREEN = 0; public static final int YELLOW = 1; public static final int RED = 2;... } shared by all instancescannot change value TrafficSignal.YELLOW  1

58 Summary: how to refer to what staticdynamic what from variable sv method sm variable dv method dm anywhere C.sv o.sv C.sm() o.sm() o.dvo.dm() static methods of C svsm() —— dynamic methods of C svsm()dvdm() Class C, o instance of C

59 Final Why can't we (as an Indiana legislator tried to pass into law in 1897)? “Variables” intended to hold fixed values (constants) should be declared final Final variables can be assigned to just once Math.PI = 3.0;

60 Final variables can be dynamic public class Ticket { private static int issued; public static int getIssued(){ return issued; } private final int number; public Ticket() { number = issued++; } public int getNumber() { return number; } ensure ticket number can't change

61 The traffic signal again public class TrafficSignal { public static final int GREEN = 0; public static final int YELLOW = 1; public static final int RED = 2; public static int nextLight(int color) { return (color + 1) % 3; } private int light; public TrafficSignal (int initial) { light = initial; }... } static method

62 Operating the signal public class TrafficSignal {... private int light; public int light() { return light; } public void change() { light = nextLight(light); } } static method invocation