3.1 data types: using objects. data type. set of values and operations on those values. primitive...

49
3.1 Data Types: Using Objects

Upload: corey-perry

Post on 02-Jan-2016

257 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

3.1 Data Types: Using Objects

Page 2: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

Data type. Set of values and operations on those values.

Primitive types. “Built-in” for a language. Basic “building blocks” Usually single values. Operations directly translate to machine instructions.

OK, but we want to write programs that process other types of data. Colors, pictures, strings, input streams, … Complex numbers, vectors, matrices, polynomials, … Points, polygons, charged particles, celestial bodies, …

2

Data Types

OperationsSet of ValuesData Type

not, and, or, xortrue, falseboolean

double

int

add, subtract, multiplyany of 264 possible reals

add, subtract, multiply-231 to 231 - 1

Page 3: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

Remember Abstraction? Hiding details…. One principle of “computational thinking.”

When we use data types, keep these things in mind: We don’t have to understand exactly how bits are stored in the

machine. We have an “information model” (or set of values), and… We have operations to use -- even if we don’t know exactly how

they’re implemented!

Question for you: If operations hide details and are a form of abstraction, can you

think of something else we’ve done in Java that is also an example of this “procedural abstraction”?

3

Data Types and Abstraction

Page 4: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

Reference type. In Java, not a simple, basic data type. Arrays are one kind of reference type. Object types are another.

– Examples: String, In “Class” means data type that’s an object

– Class and type. Object and variable.

What’s important about reference types? Object types are not part of the “core” language (perhaps part of

standard libraries). Arrays are. Object types can be defined by someone or by us. The variable “refers to” or “points to” a separate chunk of

memory. We can access things inside what’s pointed to.

– Example: int[] a = new int[10]; a.length

– Problem: int[] b; b.length

4

“Non-primitive” types

Page 5: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

5

Objects

Object. Holds a value of a particular data-type. A variable name refers to an object.

Class. The data type

Impact. Enables us to create our own data types; define operations on them; and integrate into our programs.

length, substring, comparesequence of charactersString

OperationsSet of ValuesData Type

get red component, brighten24 bitsColor

Picture get/set color of pixel (i, j)2D array of colors

Page 6: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

A Charge class. Represents a charged particle in a 2-dim space. Can use this to study “electric potential.”

Data Model. Location in a 2-dim space, so x and y values The charge at that point

Operations. Calculate potential due to this particle as some other (x,y) Convert this to a String for output

An API defines functions (known as methods) for each class: Charge (double x0, double y0, double q0) // constructor double potentialAt( double x, double y) String toString()

6

Example Data Type (Class): Charge

Page 7: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

Note! No operators like +, *, etc.

Methods / Functions. These are slightly different than previous methods These are “instance methods” Previously we wrote “static” methods

Instance methods are called “on” an object (a variable) System.out.println(); // call println on System.out String s = aCharge.toString(); // call toString on aCharge In fileIn = new In(“file.txt”); fileIn.readInt();

Ways to think about this: Send a message to an object. Tell an object to do something.

7

Methods for a Class

Page 8: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

In Java, remember: Variables must be initialized when created.

We must have a way to make this happen for “new” types.

One special instance method in the API: Charge (double x0, double y0, double q0) // constructor

This is a method called when you invoke “new” to create a new object!

You can pass parameters to control initialization. The class’ author defines the logic for this method to carry out

proper initialization.

8

Constructors

Page 9: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

9

Example: Constructors and Methods

To construct a new object: Use keyword new and name of data type.

To apply an operation: Use name of object, the dot operator, andthe name of the method.

Page 10: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

10

String Data Type

String data type. Basis for text processing.Set of values. Sequence of Unicode characters.

API.

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html

Page 11: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

11

Typical String Processing Code

Page 12: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

12

Page 13: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

Image Processing

Page 14: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

14

Color Data Type

Color. A sensation in the eye from electromagnetic radiation.

Set of values. [RGB representation] 2563 possible values, which quantify the amount of red, green, and blue, each on a scale of 0 to 255.

255255255

2550255

000

25500

105

255

0

G

105

0

255

R ColorB

0

0

105

Page 15: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

15

Color Data Type

Color. A sensation in the eye from electromagnetic radiation.

Set of values. [RGB representation] 2563 possible values, which quantify the amount of red, green, and blue, each on a scale of 0 to 255.

API. Application Programming Interface.

http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Color.html

Page 16: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

16

Albers Squares

Josef Albers. Revolutionized the way people think about color.

Homage to the Square by Josef Albers (1949-1975)

Page 17: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

17

% java AlbersSquares 9 90 166 100 100 100

Albers Squares

Josef Albers. Revolutionized the way people think about color.

Page 18: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

18

Using Colors in Java

import java.awt.Color;

public class AlbersSquares { public static void main(String[] args) { int r1 = Integer.parseInt(args[0]); int g1 = Integer.parseInt(args[1]); int b1 = Integer.parseInt(args[2]); Color c1 = new Color(r1, g1, b1);

int r2 = Integer.parseInt(args[3]); int g2 = Integer.parseInt(args[4]); int b2 = Integer.parseInt(args[5]); Color c2 = new Color(r2, g2, b2);

StdDraw.setPenColor(c1); StdDraw.filledSquare(.25, .5, .2); StdDraw.setPenColor(c2); StdDraw.filledSquare(.25, .5, .1);

StdDraw.setPenColor(c2); StdDraw.filledSquare(.75, .5, .2); StdDraw.setPenColor(c1); StdDraw.filledSquare(.75, .5, .1); }}

to access Color library

first color

second color

first square

second square

Page 19: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

19

Monochrome Luminance

Monochrome luminance. Effective brightness of a color.

NTSC formula. Y = 0.299r + 0.587g + 0.114b.

import java.awt.Color;

public class Luminance {

public static double lum(Color c) { int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); return .299*r + .587*g + .114*b; }

}

Page 20: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

20

Color Compatibility

Q. Which font colors will be most readable with which background colors on computer monitors and cell phone screens?

A. Rule of thumb: difference in luminance should be 128.

public static boolean compatible(Color a, Color b) { return Math.abs(lum(a) - lum(b)) >= 128.0;}

208256 28 14105 47

Page 21: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

21

Grayscale

Grayscale. When all three R, G, and B values are the same,resulting color is on grayscale from 0 (black) to 255 (white).

Convert to grayscale. Use luminance to determine value.

Bottom line. We are writing programs that manipulate color.

public static Color toGray(Color c) { int y = (int) Math.round(lum(c)); Color gray = new Color(y, y, y); return gray;}

round double to nearest int

Page 22: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

22

Picture Data Type

Raster graphics. Basis for image processing.

Set of values. 2D array of Color objects (pixels).

API.

(0, 0)

i

j

Page 23: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

23

Image Processing: Grayscale Filter

Goal. Convert color image to grayscale according to luminance formula.

import java.awt.Color;

public class Grayscale { public static void main(String[] args) { Picture pic = new Picture(args[0]); for (int i = 0; i < pic.width(); i++) { for (int j = 0; j < pic.height(); j++) { Color color = pic.get(i, j); Color gray = Luminance.toGray(color); pic.set(i, j, gray); } } pic.show(); } }

Page 24: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

24

Image Processing: Grayscale Filter

Goal. Convert color image to grayscale according to luminance formula.

mandrill.jpg % java Grayscale mandrill.jpg

Page 25: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

Horton got this far before Exam 2 in Spring 2008.

For exam 2, no need to look at slides after this.

Slides after this point will be covered after Exam 2.

25

Page 26: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

26

Image Processing: Scaling Filter

Goal. Shrink or enlarge an image to desired size.

Downscaling. To shrink, delete half the rows and columns.Upscaling. To enlarge, replace each pixel by 4 copies.

Page 27: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

27

Image Processing: Scaling Filter

Goal. Shrink or enlarge an image to desired size.

Uniform strategy. To convert from ws-by-hs to wt -by-ht : Scale row index by ws / wt . Scale column index by hs / ht . Set color of pixel (i, j) in target image to color of pixel

(i ws / wt , j hs / ht ) in source image.

?

source image(ws-by-hs)

target image(wt-by-ht)

i

j

i ws / wt

j hs / ht

Page 28: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

28

Image Processing: Scaling Filter

import java.awt.Color;

public class Scale { public static void main(String args[]) { String filename = args[0]; int w = Integer.parseInt(args[1]); int h = Integer.parseInt(args[2]); Picture source = new Picture(filename); Picture target = new Picture(w, h); for (int ti = 0; ti < w; ti++) { for (int tj = 0; tj < h; tj++) { int si = ti * source.width() / w; int sj = tj * source.height() / h; Color color = source.get(si, sj); target.set(ti, tj, color); } } source.show(); target.show(); }}

Page 29: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

29

Image Processing: Scaling Filter

Scaling filter. Creates two Picture objects and two windows.

% java Scale 400 200 mandrill.jpgmandrill.jpg

Page 30: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

30

More Image Processing Effects(See book and book-site)

wave filter glass filter Sobel edge detection

RGB color separation

swirl filter

Page 31: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

Objects and Reference Types: Important Issues

See textbook: pp. 352-357

31

Page 32: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

32

Important Issues about Objects and Reference Types

Study textbook: pages 352-357

References are not objects!

Aliases

Comparing objects. Don’t use ==. Use .equals()

Orphan objects, Memory Management

Page 33: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

33

OOP Context for Color

Possible memory representation.

Object reference is analogous to variable name. We can manipulate the value that it holds. We can pass it to (or return it from) a method.

255

D0

0

D1

255

D2

D0

A0magenta

0

D3

0

D4

0

D5

105

D6

105

D7

105

D8

D6

B0gray

memory address("pointer")

Page 34: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

34

OOP Context

Reference. Variable that stores the name of a thing.

Some consequences. Assignment statements copy references (not objects). The == operator tests if two references refer to same object. Pass copies of references (not objects) to functions.

– efficient since no copying of data– function can change the object

00FACADEByte of computer memory

NameThing

1CWord of TOY memory

www.princeton.eduWeb page

45-234-23310076Bank account

35 Olden StreetHome

Page 35: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

35

References

René Magritte. "This is not a pipe."

Java. This is not a color. (Where “this” means c or sienna below.)

OOP. Natural vehicle for studying abstract models of the real world.

Color sienna = new Color(160, 82, 45);Color c = sienna.darker();

Page 36: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

36

Reference variables and equality

Remember arrays? Can’t use == to see if two have the same content.

Objects. Same thing! Never use == if you want to know if they have the same content.

Use instance method equals(). All Java classes should provide a working version of equals() that takes a 2nd object as an argument.String s1 = new String("hello”);

String s2 = new String("hello”);System.out.println( s1.equals(s2) ); trueSystem.out.println( s1==s2 ); falseSystem.out.println( s1==s1 ); trueString s3 = s1;System.out.println( s1==s3 ); true

Page 37: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

37

Some things can’t be changed: Color objects, for example

Immutability. Can't change a Color object's value once created.

Consequence. Don't need to worry about aliases.

Color a = new Color(160, 82, 45);Color b = a;a = new Color(0, 0, 0);

makes a point to a different Color, but does not change b

no relevant methods in Color API

Page 38: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

38

Java objects: Some are Immutable, Some are Not

Immutability. Can't change a Color object's value once created.

We can create a new color from an old one.We can change the Color object the reference points to.The String class is immutable too.

Mutability. Can change a Picture object's value.

Java has class StringBuffer that is like String but mutable. It has an append() method, for example.

D0

D4

D8

DC

Color red = new Color(255, 0, 0);pic.set(0, 3, red);

no relevant methods in Color API

Page 39: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

Code Example

39

public static void main (String[] args) { String s1 = "Defined in main."; changeString(s1); System.out.println("String obj is now: " + s1); // see? reference still points to original object StringBuffer sb1 = new StringBuffer("Defined in main."); changeStringBuffer(sb1); System.out.println("StringBuffer obj is now: " + sb1); // see? object pointed to has be changed!} public static void changeString(String s) { s = "Changed in method"; // change is only local} public static void changeStringBuffer(StringBuffer sb) { sb.append(" -- Changed in method");}

Page 40: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

40

Conclusion from Example

Arguments that are object-references:Code inside a method can change an argument passed to it. Only if that argument allows itself to be changed (i.e. is mutable).Cannot make the object-reference point to a new object.

In other words, inside the method:The thing “pointed to” can be changed.The “pointer” cannot be changed.

This rule is same as for arrays!

Page 41: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

41

OOP Summary

Object. Holds a data type value; variable name refers to object.

In Java, programs manipulate references to objects. Exception: primitive types, e.g., boolean, int, double. Reference types: String, Picture, Color, arrays, everything

else.

Bottom line. We wrote programs that manipulate colors, pictures,and strings.

Next. We'll write programs that manipulate our own abstractions.

Page 42: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

Extra Slides

Page 43: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

43

Spectrum

import java.awt.Color;

public class Spectrum { public static void main(String[] args) { int N = Integer.parseInt(args[0]); Picture pic = new Picture(N, N); for (int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { int r = (i * 256) / N; int g = 128; int b = (j * 256) / N; Color c = new Color(r, g, b); pic.set(i, j, c); } } pic.show(); pic.save("spectrum.png"); }}

Page 44: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

44

Java Function Involving Colors

We can write Java functions that manipulate colors. Ex: return convex combination of two colors.

import java.awt.Color;public class ColorCombiner { public static Color combine(Color c1, Color c2, double beta) { int r = (int) (beta*c1.getRed() + (1-beta) * c2.getRed()); int g = (int) (beta*c1.getGreen() + (1-beta) * c2.getGreen()); int b = (int) (beta*c1.getBlue() + (1-beta) * c2.getBlue()); return new Color(r, g, b); } public static void main(String args[]) { Color c1 = new Color(127, 255, 255); Color c2 = new Color( 0, 127, 127); Color c3 = combine(c1, c2, 0.15); System.out.println("c3 = " + c3); }} % java ColorCombiner

c3 = java.awt.Color[r=19,g=146,b=146]

Page 45: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

45

Color Separation

import java.awt.Color;public class ColorSeparation { public static void main(String args[]) { Picture pic = new Picture(args[0]); int width = pic.width(); int height = pic.height();

Picture R = new Picture(width, height); Picture G = new Picture(width, height); Picture B = new Picture(width, height);

for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { Color c = pic.get(i, j); int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); R.set(i, j, new Color(r, 0, 0)); G.set(i, j, new Color(0, g, 0)); B.set(i, j, new Color(0, 0, b)); } } R.show(); G.show(); B.show(); } }

Page 46: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

46

Color Separation

ColorSeparation.java. Creates three Picture objects and windows.

Page 47: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

47

Image Processing: Swirl Filter

Swirl.java. Creates two Picture objects and windows.

Page 48: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

48

Image Processing: Swirl Filter

Goal. Create swirl special effect by setting color of output pixel (i, j) to color of some other input pixel (ii, jj).

double i0 = 0.5 * width;double j0 = 0.5 * height;

for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { double di = i - i0; double dj = j - j0; double r = Math.sqrt(di*di +dj*dj); double a = Math.PI / 256 * r; int ii = (int)(-di*Math.cos(a) + dj*Math.sin(a) + i0); int jj = (int)( di*Math.sin(a) + dj*Math.cos(a) + j0); if (ii >= 0 && ii < width && jj >= 0 && jj < height) pic2.set(i, j, pic1.get(ii, jj)); }}

Page 49: 3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building

49

Memory Management

Value types. Allocate memory when variable is declared. Can reclaim memory when variable goes out of scope.

Reference types. Allocate memory when object is created with new. Can reclaim memory when last reference goes out of scope. Significantly more challenging if several references to same

object.

Garbage collector. System automatically reclaims memory;programmer relieved of tedious and error-prone activity.