CSE 142, Spring 2013 .edu

[Pages:17]CSE 142, Spring 2013

Chapter 8 Lecture 8-3: Encapsulation, this

reading: 8.5 - 8.6 self-checks: #13-17

exercises: #5

Copyright 2008 by Pearson Education

Don't need to know this

Abstraction

Can focus on this!!

2

Copyright 2008 by Pearson Education

The toString method

tells Java how to convert an object into a String

Point p1 = new Point(7, 2); System.out.println("p1: " + p1); // the above code is really calling the following: System.out.println("p1: " + p1.toString());

Every class has a toString, even if it isn't in your code.

Default: class's name @ object's memory address (base 16) Point@9e8c34

4

Copyright 2008 by Pearson Education

toString syntax

public String toString() { code that returns a String representing this object;

}

Method name, return, and parameters must match exactly.

Example: // Returns a String representing this Point. public String toString() { return "(" + x + ", " + y + ")"; }

5

Copyright 2008 by Pearson Education

Private fields

A field can be declared private.

No code outside the class can access or change it. private type name;

Examples: private int id; private String name;

Client code sees an error when accessing private fields:

PointMain.java:11: x has private access in Point System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");

^

6

Copyright 2008 by Pearson Education

Accessing private state

We can provide methods to get and/or set a field's value:

// A "read-only" access to the x field ("accessor") public int getX() {

return x; } // Allows clients to change the x field ("mutator") public void setX(int newX) {

x = newX; }

Client code will look more like this:

System.out.println("p1: (" + p1.getX() + ", " + p1.getY() + ")"); p1.setX(14);

7

Copyright 2008 by Pearson Education

Encapsulation

encapsulation: Hiding implementation details of an object from its clients.

Encapsulation provides abstraction.

separates external view (behavior) from internal view (state)

Encapsulation protects the integrity of an object's data.

8

Copyright 2008 by Pearson Education

Point class, version 4

// A Point object represents an (x, y) location. public class Point {

private int x; private int y;

public Point(int initialX, int initialY) { x = initialX; y = initialY;

}

public double distanceFromOrigin() { return Math.sqrt(x * x + y * y);

}

public int getX() { return x;

}

public int getY() { return y;

}

public void setLocation(int newX, int newY) { x = newX; y = newY;

}

public void translate(int dx, int dy) { x = x + dx; y = y + dy;

} }

10

Copyright 2008 by Pearson Education

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download