Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf ·...

45
Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Chapter 9/Appendix A: Mutable Objects and Graphics

Transcript of Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf ·...

Page 1: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Think Java:

How to Think Like a Computer

Scientist

5.1.2

by Allen B. Downey

Chapter 9/Appendix A:

Mutable Objects and Graphics

Page 2: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Falling Objects Program

How far has the rock fallen after 2.63 seconds?

How far has the soccer ball travelled horizontally after 0.75 seconds?

Page 3: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

3

Chapter Topics

Chapter 9 discusses the following main topics:– Point objects– Instance variables– Objects as parameters– Rectangles– Objects as return types– Aliasing– null– Garbage collection– Objects vs primitives

• Download lab9.zip and extract for lecture demo

Page 4: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Packages• Java libraries are divided into packages

– java.lang contains most classes used so far• String, Math

– java.util contains the Scanner class

– java.awt (today)• Abstract Window Toolkit (AWT)

• contains classes for windows, buttons, graphics, etc.

• All import statements appear at the beginning of the program, outside the class definition.

Page 5: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Point objects• A point is two numbers (coordinates)

– treat collectively as a single object.

– (0, 0) indicates the origin

– (3,4) indicates a point 3 units to left and 4 units above origin

• What is the coordinate of

this point?

• In Java, a point is represented

by a Point object

Page 6: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Create a Point in Java

• To create a new point, you have to use new:

– First line declares a variable– Second line:

• invokes new• specifies the type• provides arguments

• result of new is a reference to the new point– dot contains a reference to the newly-created object.

dot;

dot

Page 7: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Memory Diagram of dot

• name of the variable (dot)

– appears outside the box

• value appears inside the box

– value is a reference (shown as arrow)

– arrow points to object we're referring to

• big box shows the newly-created object with the two values in it. The names x and y are the names of the instance variables.

dot

Page 8: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Instance Variables are…

• the pieces of data that make up an object

• each object is an instance of its type

– has its own copy of the instance variables.

Point center = new Point(1,8);

– we can make any number of point objects to draw a figure, or compute the volume of a solid

dot

Page 9: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Read a value from an object

• Specify the object you want to examine

– Then specify which instance variable you want

– int x = dot.x;

– int y = center.y;

– go to the object dot refers to, get the value of x.

– no conflict between the local variable named x and the instance variable named x

• Another example– System.out.println(dot.x + ", " + dot.y);

Page 10: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Objects as parameters of methods

• You can pass an object to a method, such as– printPoint(dot);

• Method is defined with a Point parameter to receive argument

• Another example: – System.out.println(distance(dot, center));

Page 11: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Rectangles

• Rectangles are similar to points

– each has four instance variables: x, y, width and height

– works pretty much the same as points, but with more info

Page 12: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Returning Objects from Methods

• Methods can return objects

• Above method uses new to create a new object

– immediately uses the result as the return value

Page 13: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Unlike String, most Objects are mutable

• Change the contents of an object

– make an assignment to one of its instance variables

– “move” a rectangle without changing its size

Page 14: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Encapsulate into a Method

• Using a method to move a Rectangle

• Prints the message

Page 15: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Aliasing• It is possible to have multiple variables refer to the same

object.

• box1 and box2 refer to the same object

• Like a person with multiple names:– Joseph Barnet, aka "Jack the Ripper"

Page 16: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Consequence of Aliasing

• When two variables are aliased, any changes that affect one variable also affect the other.

• Whatever changes are made to box1

– also apply to box2

– in general, you should avoid aliasing where possible

Page 17: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

The null keyword

• Object variables contain references to an object

• null means "no object"

• null is represented by a square with no arrow

dot

dot

Page 18: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Null Pointer Exception

• If you try to use a null object, Java throws an exception

• It is legal to pass null objects to or from methods

• Can indicate an empty set, or an error condition and handled properly

if (dot != null){

…dot refers to actual object, ok to proceed.

}

dotdot

dot

Page 19: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Garbage Collection

• When no variable refers to an object

• The point object (3,4) cannot be accessed

• Stranded in memory

• Periodically removed by Garbage Collector

dotdot

dot

Page 20: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Objects vs Primitives

• Primitive types: int, char, double, boolean– begin with lower case letter

– value is stored in variable: int x = 3;

– can only contain one piece of data

• Object types: String, Scanner, Point, Rectangle– begin with upper case letter

– reference to object is stored in variable• use new to allocate space for an object

– contain multiple pieces of data• and methods to process the data

– You can add new object types to Java!

Page 21: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Lab 9 Coding – Particle Class

• A Particle object is like a point– has an xPos, yPos for the position

– also has additional info for velocity• xVel, yVel – speed in x and y directions

• You create a particle by giving all four pieces to the constructor:– Particle rock = new Particle(10,20,50,7);

• rock starts at location (10,20)

• with a horizontal velocity of 50

• and a vertical velocity of 7

• straight for the back of his head!

we call this a

"constructor"

because it

"creates" an

object for us

Page 22: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Particle class methods

• Unlike Point and Rectangle objects, we can't modify the instance variables of Particle objects directly

– rock.x = 85; // illegal

– int x = rock.x; // also illegal

• Instead, there are methods to do that for us

– rock.setXPosition(85);

– int x = rock.getXPosition();

Page 23: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Particles move through space/time

• A Particle object has velocity, so it moves

• If you want to see where the Particle is in the future, use the passTime method

– rock.passTime(3.5); // let 3.5 seconds pass

• Where is the rock now?

– System.out.println("x = " + rock.getXPosition( ) +

"y = " + rock.getYPosition( ) );

Note: Particles are subject to gravity as well!

Page 24: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Start Lab 9 Part AWork the problems on handout

• then do coding (Particle) problem

• if you finish early, start work on assignment 9 or finish work from last week

Page 25: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Graphics

• See Appendix A of our online text

• Basics of 2D Graphics

• Today’s Lab - DrawFlag

Page 26: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Additional Classes we need

the window for our canvas

the canvas we will draw on

adds canvas to frame

shows the window with canvas

called by JVM (not main)

adds graphics content to canvas

Page 27: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

In previous code example

• The first lines import the classes we need to usejava.awt – abstract window toolkit, more universal (JFrame)javax.swing. – more lightweight, not all browsers support

• MyCanvas extends Canvas,– a MyCanvas object is a special kind of Canvas, we tailor for our graphics

• In main we– Create a JFrame, which is a window that can contain the canvas,

buttons, menus, and other window components;– Create MyCanvas, set its width and height, and add it to the frame; and

• Display the frame on the screen.• paint

– a special method that gets invoked when MyCanvas needs to be drawn.– draws a black circle:

Page 28: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Drawing Shapes

• A Canvas has an associated Graphics object that may be used to draw lines and shapes.

• Java allows drawing of lines and graphical shapes such as rectangles, ovals, and arcs.

Page 29: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

XY Coordinates• The location of each pixel in a component is identified with an

X coordinate and a Y coordinate.

• The coordinates are usually written in the form (X, Y).

• Unlike Cartesian coordinates, the upper-left corner of a drawing area is (0, 0).

• The X coordinates increase from left to right, and the Y coordinates increase from top to bottom.

• When drawing a line or shape on a component, you must indicate its position using X and Y coordinates.

Page 30: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Graphics Objects

• Each component has an internal object that is derived from the Graphics class, which is part of the java.awt package.

• This object has numerous methods for drawing graphical shapes on the surface of the component.

Page 31: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Graphics Objects• Some of the methods of the Graphics class:

– setColor(Color c) – Sets the drawing color for this object.

– getColor() – Returns the current drawing color for this object.

– drawLine(int x1, int y1, int x2, int y2)

• Draws a line on the component

– drawRect(int x, int y, int width, int height)

• Draws the outline of a rectangle on the component.

– fillOval(int x, int y, int width, int height)

• Draws a filled oval.

– drawString(String str, int x, int y)

• Draws the string passed into str using the current font.

Page 32: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Graphics Objects

• In order to call these methods, you must get a reference to a component’s Graphics object.

• One way to do this is to override the paint method.

• You can override the paint method in any class that is derived from: – JApplet

– JFrame

– Any AWT class

• The paint method is responsible for displaying, or “painting,” a component on the screen.

Page 33: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Graphics Objects

• The paint method is automatically called

– when the Canvas is first displayed and

– any time the Canvas needs to be redisplayed.

• The header for the paint method is:public void paint(Graphics g)

• The method’s argument is a Graphics object, which is automatically passed by the calling component.

• Overriding the paint method, allows drawing of graphics on the Graphics object argument.

Example: LineDemo.java, LineDemo.html

Page 34: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Drawing a Line

public void paint(Graphics g) {

g.drawLine(10,20,100,200);

(10,20)

(100,200)

Page 35: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Drawing a Rectangle (Shape, not Object)

public void paint(Graphics g) {

g.drawLine(10,20,100,200);

// draw a filled rectangle

g.fillRect(50,100,20,40);

(50,100)

widh = 20,

height = 40

Page 36: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Drawing a Rectangle (Shape, not Object)

public void paint(Graphics g) {

g.drawLine(10,20,100,200);

g.fillRect(50,100,20,40);

// draw an outline line of a rectangle

g.drawRect(100,200,75,50);

(100,200)

widh = 75,

height = 50

Page 37: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Ovals and Bounding Rectangles

• Ovals are created by drawing the oval inside of a “bounding rectangle”.

• This rectangle is invisible to the viewer of the Graphicsobject. g.fillOval(x, y, width, height);

(x,y)

Width

Height

Page 38: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Arcs• Arcs are drawn from the 90 degree position

counterclockwise and can be filled or unfilledg.drawArc(0, 20, 120, 120, 0, 90);

g.fillArc(0, 20, 120, 120, 0, 90);

• The fillArc and drawArc take six integers as parameters:drawArc(int x, int y, int width, int height, int

start, int end)

Page 39: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Polygons -- I• You can make a Polygon object

// make a polygon and draw it

Polygon p = new Polygon();

p.addPoint(10,20); p.addPoint(10,40);

p.addPoint(50,60);

• You then draw your Polygon objectg.setColor(Color.blue);

g.drawPolygon(p);

• use g.drawPolygon to draw an outline

• use g.fillPolygon to draw a shaded polygon

Page 40: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Polygons -- II• Polygons can also be drawn using arrays of integers

representing x, y coordinates

int[]xCoords={60,100,140,140,100,60,20,20};

int[]yCoords={20,20,60,100,140,140,100,60};

// Draw the polygon.

g.drawPolygon(xCoords, yCoords, 8);

how many

points in

array to draw

Page 41: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Drawing with a Rectangle object

• To draw with a Rectangle object, just give the draw method the fields of the Rectangle.

// draw an oval shape using g.drawOval on a Rect

Rectangle box = new Rectangle(100,100, 30,30);

g.drawOval(box.x, box.y, box.width, box.height);

• Or write a homemade method to save typingdraw(g, box);

Page 42: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Translating and drawing

• Rectangles have a translate method

– makes it easy to reposition and draw another

– like a stamp, you can print many rectangles

box.translate(30,0); // move rectangle

draw(g, box);

box.translate(30,0); // move rectangle

draw(g, box);

Page 43: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Using loops to draw many copies

• Draw a row of 5 ovals using a loop

int x = 0;

while (x < 5)

{

box.translate(30,0); // move rectangle

draw(g, box);

x++;

}

Page 44: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Lab 9B Flag Drawing

• This will be another exercise in methods, generalizing so you can print many copies of each flag.

Page 45: Chapter 9/Appendix A: Mutable Objects and Graphicstomrebold.com/csis10a/ch09/lec9.pdf · 2015-10-16 · java.awt –abstract window toolkit, more universal (JFrame) javax.swing. –more

Assignment 9

• For assignment 9, you get to write a method to draw a house and use it to print multiple copies