Aqua Phoenix
     >>  Research >>  OOP  


20. Building data objects

20.1 Summary

  • A data object consists of variables that hold data and methods that retrieve, save, and manipulate data
  • Introduction to private, public, and protected data types

20.2 Contents

20.2.1 A data object consists of variables that hold data and methods that retrieve, save, and manipulate data

[Discussion of a single data object that holds name, address, phone number, birthday, etc.]

20.2.2 Introduction to private, public, and protected data types

We have been using the keyword "public" many times so far in conjunction with declaring methods. We have done so, because we needed to access these methods from outside the class. When we write an expression such as "button.getLabel()", we are retrieving the contents of some data element in the button from outside the button, e.g. from an applet. So far, we have taken this concept for granted. However, some methods in some objects are not declared as publically accessible methods, but instead as private. If "getLabel()" were to be declared privately, then we would not be able to access it from the outside. The compiler would simply return an error.

Why would we restrict access to methods? Take an object for an example, that stores data. Data is stored and retrieved via methods in the object. However, data is not simply dumped into the object; the object makes sure that data is stored in a correct fashion. In order to organize data, the object has certain variables that may only be changed by the object itself. Let's assume the object contains a list of 10 names. Somewhere in the object, the number 10 is stored as the length of the list. What if we simply overwrote that value by saying "object.length = 5". This would lead to some corruption in the data object. All of the sudden, only 5 data members are accessible in the object, even though there are 10. For that reason, certain variables and methods are declared as private members, which means that only the class itself is allowed to change the value.

Other than the private and public declaration, there is a third declaration by the name of "protected". Protected methods and variables can be unrestrictedly from the class that defines it, as well as all sub-classes of this class. If some complicated class had a few helper sub-classes, these classes would be able to read and write the protected component, whereas all other alien classes would not.

The discussion of public, private, and protected leads to a generalization of what can be accessed within a class. So far, we have been accessing methods in classes as in "object.getSomething()". If a variable (as opposed to a method) is declared as public or protected in a class, we can also access these variables in the same fashion. Since variables themselves do not take arguments, we access them without the parentheses, e.g. "object.count". This would return the value for variable "count" in Object "object".