CSE 142, Spring 2013 .edu

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

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

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

Google Online Preview   Download