08 - 02/01/09 05:51:29 CS 61B: Lecture 8 Friday, February...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
02/01/09 05:51:29 1 08 CS 61B: Lecture 8 Friday, February 6, 2009 Today’s reading: THE "public" AND "private" KEYWORDS =================================== Thus far, we’ve usually declared fields and methods using the "public" keyword. However, we can also declare a field or method "private". A private method or field is invisible and inaccessible to other classes, and can be used only within the class in which the field or method is declared. Why would we want to make a field or method private? (1) To prevent data within an object from being corrupted by other classes. (2) To ensure that you can improve the implementation of a class without causing other classes that depend on it to fail. In the following example, EvilTamperer tries to get around the error checking code of the Date class by fiddling with the internals of a Date object. public class Date { | public class EvilTamperer { private int day; | public void tamper() { private int month; | Date d = new Date(1, 1, 2006); | private void setMonth(int m) { | d.day = 100; // Foiled!! month = m; | d.setMonth(0); // Foiled again!! } | } | } public Date(int month, int day) { | [Implementation with | error-checking code here.] | } } However, javac won’t compile EvilTamperer, because the Date class has declared its vulnerable parts "private". setMonth is an internal helper method used within the Date class, whereas the Date constructor is a public part of the interface of the Date class. Error-checking code in the constructor ensures that invalid Dates are not constructed. Here are some important definitions. The _interface_ of a class is a set of prototypes for public methods (and sometimes public fields), plus descriptions of the methods’ behaviors. An _Abstract_Data_Type_ (ADT) is a class that has a well-defined interface, but
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 2

08 - 02/01/09 05:51:29 CS 61B: Lecture 8 Friday, February...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online