RU beehive logo ITEC dept promo banner
ITEC 120
2008spring
ibarland,
jdymacek

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect09a
public vs private

Review: we can write a method swapAge (which modifies fields), but we can't write a method swapDogs (which modifies local variables).

public vs. private

Consider the class Die from lab08b—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!

Die myd6 = new Die();
myd6.roll();
myd6.getFace()
myd6.setFace(93); // Setter will make sure this is at least sane (if not fair)
However, having the setter check for bad inputs doesn't solve the problem entirely:
myd6.face = 93;  // Cheating, from the Code Pad!
If we declare the field face to be private, then this becomes illegal to change from outside the class (e.g. the Code Pad, or any other class like PairODice).
class Die {
  int NUM_SIDES = 6;

  private int face = NUM_SIDES;

  //...
  }

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.


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


©2008, Ian Barland, Radford University
Last modified 2008.Mar.17 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme