08 - 09/15/10 18:34:00 08 CS 61B: Lecture 8 Wednesday,...

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

View Full Document Right Arrow Icon
09/15/10 18:34:00 1 08 CS 61B: Lecture 8 Wednesday, September 15, 2010 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.

This note was uploaded on 01/10/2012 for the course CS 61B taught by Professor Canny during the Fall '01 term at Berkeley.

Page1 / 2

08 - 09/15/10 18:34:00 08 CS 61B: Lecture 8 Wednesday,...

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