objects

55
1 Objects

Upload: ivana

Post on 14-Jan-2016

36 views

Category:

Documents


0 download

DESCRIPTION

Objects. Recall: Data types. data type : A category of data values. Example: integer, real number, string Java data types are divided into two sets: primitive types : Java's 8 built-in simple data types for numbers, text characters, and logic. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Objects

1

Objects

Page 2: Objects

2

Recall: Data types

data type: A category of data values. Example: integer, real number, string

Java data types are divided into two sets: primitive types: Java's 8 built-in simple data

types for numbers, text characters, and logic. boolean, char, byte, short, int, long,

float, double object types: All other types!

e.g., Scanner, System, String, Math

Page 3: Objects

3

Object types

So far, we have seen: variables, which represent data (categorized by types) methods, which represent behavior

object: An variable that contains data and behavior. There are variables inside the object, representing its data. There are methods inside the object, representing its behavior.

class: Basic building block of Java programs (what we have seen so far)

AND Data types for objects

Page 4: Objects

4

Example object types

Theoretical examples: A class Person could represent objects that store a name,

height, weight, hair color, IQ, etc… A class Laptop could represent objects that store speed,

screen size, color, dimensions, brand, etc…

Examples from Java: The class String represents objects that store text

characters. The class Scanner represents objects that can tokenize

streams of characters.

Page 5: Objects

5

Point objects

Page 6: Objects

Point object

Data stored in each Point object:

Useful methods in each Point object:

6

the point's y-coordinatey

the point's x-coordinatex

DescriptionField name

how far away the point is from point pdistance(p)

adjusts the point's x and y by the given amountstranslate(dx, dy)

sets the point's x and y to the given valuessetLocation(x, y)

DescriptionMethod name

Page 7: Objects

7

Constructing objects

construct: To create a new object. Objects are constructed with the new keyword.

Constructing objects, general syntax:<class> <name> = new <class>(<arguments>);

Examples:Point p = new Point(7, -4);Scanner console = new Scanner(System.in);

Q: Wait a minute! Why don’t we construct strings with new? A1: Strings are one of the most commonly used objects, so they

have special syntax (quotation marks) to simplify their construction. A2: Also, you can if you want to: String s = new String(“hi”);

Page 8: Objects

8

Point object: Construction

Constructing a Point object, general syntax:Point <name> = new Point(<x>, <y>);

Point <name> = new Point(); // the origin, (0, 0)

Examples:Point p1 = new Point(5, -2);

Point p2 = new Point();

Page 9: Objects

Representing objects

So far, I have drawn primitive types like this:

int x = 7;

7X:

Page 10: Objects

Representing objects

I will represent object types like this:

Point p = new Point(7,3);

p:7 3x: y:

Variable, with slot in memory Reference, a

pointer to the object’s data

Data, in another part of memory

Fields

Page 11: Objects

References

Object variables are references to the location in memory where their data resides.

We draw references as pointers. Actually, p stores the address of the location

in memory where its data is.

p:7 3x: y:

Variable, with slot in memory Reference, a

pointer to the object’s data

Data, in another part of memory

Fields

Page 12: Objects

Constructing an object

What happens when the following call is made?Point p1 = new Point(7, 2);

12

p1: y:x: 7 2

Page 13: Objects

null objects

null is a value for all object types that says,

“this object is a reference to nothing at all” We draw null objects with a slash Note that null objects

have no memory reserved for their data!

Point p1 = null;

13

p1:

Page 14: Objects

14

Calling methods on objects

Since the methods are bundled in the objects, calling these methods requires specifying which object we are talking to.

Calling a method of an object, general syntax:<variable>.<method name>(<parameters>)

The results may vary from one object to another.

Examples: String s1 = “Homey da Clown”; String s2 = “Bubbles the clown”; System.out.println(s1.length()); // prints 14 System.out.println(s2.length()); // prints 17

Page 15: Objects

15

Calling methods on objects

Since the methods are bundled in the objects, calling these methods requires specifying which object we are talking to.

Calling a method of an object, general syntax:<variable>.<method name>(<parameters>)

The results may vary from one object to another.

Examples: Point p0 = new Point(0, 0); Point p1 = new Point(7, 3); Point p2 = new Point(2, -2); System.out.println(p1.distance(p0)); // 7.62 System.out.println(p2.distance(p0)); // 2.83

Page 16: Objects

Dereferencing

When we use the “.” operator on an object, we access the stuff (methods and/or data) that the object references (or points to).

This is called dereferencing.

The “.” operator is the dereferencing operator.

Page 17: Objects

Three kinds of method calls

We have seen three ways to call methods:

Type: No ‘.’ used <class>.<method> <variable>.<method>

When it’s used: For methods defined in the same class as they’re called

For static methods defined in another class

For non-static or instance methods defined in another class

Examples: myMethod(); Math.max(a,b) myString.length()

Integer.parseInt(“6”) console.nextInt()

Server.gcd(15,12) myPoint.translate(2,2)

Page 18: Objects

Fields

Fields are variables that contain data for an object. Since the fields are bundled in the objects, referring to

fields requires specifying an object.

Referring to the field of an object, general syntax:<variable>.<field name>

Examples:Point p = new Point(7, 3); // p = (7,3)

p.x = 2; // p = (2,3) p.y = p.y + 10; // p = (2,13)

// displays “(2, 13)” System.out.println(“(“ + p.x + “, “ + p.y + “)”);

Page 19: Objects

19

Using Point objects: Exampleimport java.awt.*;

public class PointMain { public static void main(String[] args) { // construct two Point objects Point p1 = new Point(7, 2); Point p2 = new Point(4, 3);

// print each point and their distance apart System.out.println("p1 is " + p1); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); System.out.println("distance = " + p1.distance(p2));

// translate the point to a new location p2.translate(1, 7); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); System.out.println("distance = " + p1.distance(p2)); }}

To use the Point class, you have to import it from the java.awt package in Java.

Page 20: Objects

20

Using Point objects: Exercise Write a method computePerimeter that computes a right triangle's

perimeter given two integer side lengths (a and b). The perimeter is the sum of the triangle's side lengths a+b+c.

Example: Given side lengths of 12 and 5, the method should return 30.

Page 21: Objects

21

Using Point objects: Solution public static double computePerimeter(int a, int b) { Point p1 = new Point(); // 0, 0 Point p2 = new Point(a, b); double c = p1.distance(p2); return a + b + c; }

Page 22: Objects

Common Programming Error

The dreaded NullPointerException

Point p = null;p.x = 7; // Error!p.setLocation(0,0); // Error!

If you try to dereference a null object, it will cause a NullPointerException. Why?

This is a very common error, but one nice thing about Java is that it is often fairly easy to fix this kind of error (in my experience).

Page 23: Objects

23

Classes and objects

Page 24: Objects

24

Big idea: Abstraction

abstraction: A distancing between ideas and details. How do objects provide a level of abstraction?

You use abstraction every day! Do YOU know how your iPod works?

?? ???

Page 25: Objects

25

Classes are like blueprints

Music player #1

state: station/song, volume, battery life

behavior: power on/off change station/song change volume choose random song

Music player #2

state: station/song, volume, battery life

behavior: power on/off change station/song change volume choose random song

Music player #3

state: station/song, volume, battery life

behavior: power on/off change station/song change volume choose random song

Music player blueprint

state: station/song, volume, battery life

behavior: power on/off change station/song change volume choose random song

Page 26: Objects

26

Recall: Point class

Constructing a Point object, general syntax:Point <name> = new Point(<x>, <y>);

Point <name> = new Point(); // the origin, (0, 0)

Examples:Point p1 = new Point(5, -2);

Point p2 = new Point();

Page 27: Objects

27

Recall: Point class

Data stored in each Point object:

Useful methods in each Point object:

the point's y-coordinatey

the point's x-coordinatex

DescriptionField name

how far away the point is from point pdistance(p)

adjusts the point's x and y by the given amountstranslate(dx, dy)

sets the point's x and y to the given valuessetLocation(x, y)

DescriptionMethod name

Page 28: Objects

28

Point classPoint class

state: int x, y

behavior: distance(Point p) equals(Point p) setLocation(int x, int y) toString() translate(int dx, int dy)

Point object #1

state: int x, y

behavior: distance(Point p) equals(Point p) setLocation(int x, int y) toString() translate(int dx, int dy)

Point object #2

state: int x, y

behavior: distance(Point p) equals(Point p) setLocation(int x, int y) toString() translate(int dx, int dy)

Point object #3

state: int x, y

behavior: distance(Point p) equals(Point p) setLocation(int x, int y) toString() translate(int dx, int dy)

Page 29: Objects

instances

Definition: An object is an instance of its class.

Each instance has its own local copy of the state and behavior defined in the class template.

Example: each Point object has its own x,y coordinates, and its own setLocation method.

Page 30: Objects

30

Value vs. reference semantics

Page 31: Objects

Recall: Value semantics

value semantics: Behavior where variables are copied when assigned to each other or passed as parameters. Primitive types in Java use value semantics. Modifying the value of one variable does not affect other.

Example:int x = 5;

int y = x; // x = 5, y = 5

y = 17; // x = 5, y = 17

x = 8; // x = 8, y = 17

31

Page 32: Objects

Reference semantics

reference semantics: Behavior where variables refer to a common value when assigned to each other or passed as parameters. Object types in Java use reference semantics. Object variables do not store an object; they store the address of

an object's location in the computer memory. We graphically represent addresses as arrows.

Example:Point p1 = new Point(3, 8);

32

8y:3x:p1

Page 33: Objects

Reference semantics

If two object variables are assigned the same object, the object is NOT copied; instead, the object’s address is copied. As a result, both variables will point to the same object. Calling a method on either variable will modify the same object.

Example:Point p1 = new Point(3, 8);

Point p2 = p1;

p2.setLocation(1, 2);

33

83

p2

y:x:p1 1 2

Page 34: Objects

Reference semantics: Why?

Objects have reference semantics for several reasons: efficiency: Objects can be large and bulky. Having to copy them

every time they are passed as parameters would slow down the program.

sharing: Since objects hold important state, it is often more desirable for them to be shared by parts of the program when they're passed as parameters. Often we want the changes to occur to the same object.

34

Page 35: Objects

Reference semantics: Example

Point p1 = new Point(3, 8);Point p2 = new Point(2, -4);Point p3 = p2;

How many unique objects are there? How do you know that? Two, because objects are only created with the new keyword.

If we change p3, will p2 be affected and vice versa? Yes.

35

8

p2

y:3x:p1

-4y:2x:

p3

Page 36: Objects

Reference semantics: Example If two variables refer to the same object, modifying one of

them will also make a change in the other:

p3.translate(5, 1);System.out.println("(" + p2.x + " " + p2.y + ")");

Output:(7, -3)

36

-4-32

8

p2

y:3x:p1

y:x:

p3

7

Page 37: Objects

Objects as parameters

When an object is passed as a parameter, the object is not copied. The same object is referred to by both the original variable and the method's parameter. If a method is called on the parameter, it will affect the original

object that was passed to the method.

37

Page 38: Objects

Objects as parameters: Example Example:

public static void main(String[] args) { Point p1 = new Point(2, 3); move(p1);}

public static void move(Point p) { p.setLocation(-1, -2);}

38

p1 y:x:

p

2 3-1 -2

Page 39: Objects

Program mystery

What does this code do?public static void main(String[] args) {

int a = 7;

int b = 35;

System.out.println(a + " " + b);

int temp = a;

a = b;

b = temp;

System.out.println(a + " " + b);

}

39

Page 40: Objects

Swapping values

Swapping is a common operation, so we might want to make it into a method.

public static void main(String[] args) { int a = 7; int b = 35; System.out.println(a + " " + b);

// swap a with b swap(a, b);

System.out.println(a + " " + b);}

public static void swap(int a, int b) { int temp = a; a = b; b = temp;}

Does this work? Why or why not?

40

Page 41: Objects

Let’s try swapping objects

public static void main(String[] args) { Point p1 = new Point(1, -1); Point p2 = new Point(2, 0); System.out.println(p1 + " " + p2);

// swap a with b swap(p1, p2);

System.out.println(p1 + " " + p2);}

public static void swap(Point a, Point b) { Point temp = a; a = b; b = temp;}

Does this work? Why or why not?

Page 42: Objects

A solution for swapping Point objects

public static void main(String[] args) { Point p1 = new Point(1, -1); Point p2 = new Point(2, 0); System.out.println(p1 + " " + p2);

// swap a with b swap(p1, p2);

System.out.println(p1 + " " + p2);}

public static void swap(Point a, Point b) { Point temp = new Point();

temp.setLocation(a.getX(), a.getY()); a.setLocation(b.getX(), b.getY()); b.setLocation(temp.getX(), temp.getY());}

Page 43: Objects

Wrapper Classes

Page 44: Objects

Wrapper classes

Wrapper classes are object types that correspond to each primitive type

Two important methods in Wrapper classes: parseInt(String s) (or parseDouble, parseLong …) intValue() (or doubleValue(), longValue(), …)

Important fields: MAX_VALUE, MIN_VALUE

Primitive Type Wrapper Class

int Integer

long Long

double Double

boolean Boolean

char Character

Page 45: Objects

Converting between primitive and Wrapper types You can wrap a int in an Integer by

assignment:int x = 17;Integer wrapX = new Integer(x); Integer wrapX2 = x; // shorthand

To get an int value out of an Integer object:Integer x = new Integer(17);int unwrappedX = x.intValue();int unwrappedX2 = x; // shorthand

Page 46: Objects

Wrapper classes for swapping ints

public static void main(String[] args) { Integer a = 7; Integer b = 35; System.out.println(a + " " + b);

// swap a with b swap(a, b);

System.out.println(a + " " + b);}

public static void swap(Integer a, Integer b) { Integer temp = a; a = b; b = temp;}

What’s wrong with this version?

Page 47: Objects

Mutable and Immutable objects Definition: An immutable object is an object whose

state cannot be modified after it is created.

The String class and all the wrapper classes are immutable in Java. As a result, we can’t use the wrapper classes to solve the swap

problem for primitive types. We’ll come back to swapping primitive objects later.

Point objects are mutable (ie, not immutable) setLocation and translate change their state We can use this fact to make the swap method work

Page 48: Objects

48

Madness to the method

The methods that appear to modify a string (substring, toLowerCase, toUpperCase, etc.) actually create and return a new string.

String s = "lil bow wow";s.toUpperCase();System.out.println(s); // output: lil bow wow

vs.

String s = "lil bow wow";s = s.toUpperCase();System.out.println(s); // output: LIL BOW WOW

Page 49: Objects

Exercises

Write a method to determine the slope of the line that passes between two points.

Write a method to compute the dot-product (or inner product) of two points.

Write a method to return a point’s mirror image across the x axis.

Given an int called scale, write a method to magnify a point so that its distance from the origin is multiplied by scale.

Page 50: Objects

Operators and object types

Page 51: Objects

How not test equality of objects DO NOT DO THIS:

public static boolean testEquals(Point p1, Point p2)

{if(p1==p2) {

return true;} else {

return false;}

}

BAD

Page 52: Objects

How not test equality of objects Objects store references, or addresses. Comparing two objects with == will test if they

have the same address. This is NOT what you want.

public static boolean testEquals(Point p1, Point p2)

{if(p1==p2) {

return true;} else {

return false;}

}

BAD

Page 53: Objects

Why so bad?

Point p1 = new Point(7, 2);Point p2 = new Point(7, 2);

Is p1==p2 true or false?It’s false: they point to different spots in

memory. So they store different addresses.But we want it to be true , obviously!

p1: y:x: 7 2

p2: y:x: 7 2

Page 54: Objects

The equals method

All classes in Java have a built-in equals method

For the Point class:

p1.equals(p2)

This returns true if p1 and p2 have the same data

It doesn’t matter if they reference different locations in memory

Likewise, use !p1.equals(p2) instead of p1!=p2

Page 55: Objects

Object and primitive types: a comparison (so far)

Object types Primitive types

Constructed with the new keyword Values don’t need to be constructed

References to memory location that stores their data

Store data directly in memory slot

Can be null (have no data) Cannot be null

Can cause NullPointerExceptions Cannot cause NullPointerExceptions

Contain state and behavior Contain state only

Use reference semantics Use value semantics

Use equals() method Use ==, !=