RU beehive logo ITEC dept promo banner
ITEC 120
2007fall
ibarland,
jdymacek

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect08c
public vs private

public vs. private

Consider the class Die from lab08a—printing: Pair O' Dice. It has a method void roll(), which chooses a random number in 1..6, and sets the current face to be that. In turn, the method setFace actually does that. There is a difference between these two methods though: one we intend for other people to use, and the other is for internal use, and it would be cheating for other people to call it!

Similarly, the Date methods isInLeapYear() and isValid() are arguably for internal-use-only (users of the class might reasonable expect that they only ever see valid Date objects, and yet still inside the class we need to do internal checks for validity; in turn isInLeapYear() was just a helper function for isValid()).

We can make these assumptions clear: every field and method can be labeled with an adjective public or private:

What this means for us: From now on, every method and field should be declared either public or private.

Finish previous topics

We'll also finish discussing more of the topics mentioned in lect08a—References as Values: passing arrows to functions and lect08b—== vs .equals: comparing references.


1

In fact, you might wonder if there is some “very-private” modifier which means “The method/field can only be accessed by this object itself”. Java does not have such a concept.

While such a protection-level is a very common design goal, and it makes sense from a pure object-oriented mindset, Java's philosophy is that if a programmer wants to violate privacy expecatations between PizzaServer, and that programmer has access to the source code for class PizzaServer, then that programmer could always do so: they'd just change the modifier from “very-private” to merely private.

If you ever design your own language though, it's worth not taking this for granted. Many features in programs are there to help protect programmers from themselves. (Declaring types in advance is one such feature.)

     

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2007, Ian Barland, Radford University
Last modified 2007.Oct.11 (Thu)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme