
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Properties
|
73
You may be saying, “Wait a minute! I thought class properties cannot be accessed
via instances but only directly through the class. Why does the code access
numSides
through the box1 and box2 instances?” You are correct that class properties cannot be
accessed directly via an instance. The following is invalid:
box2.numSides
However, Example 4-1 does not access the class property numSides directly through
an instance. Instead, it accesses the class property through a method, getNumSides( ),
which is accessible to instances of the class. And if you’re wondering, “Is there such a
thing as a static method?” Yes, there is. We’ll discuss static methods later.
Within a single class, the same identifier cannot be used for a class
property and an instance property. Attempting to create two proper-
ties with the same name, whether class or instance properties, always
causes a compile-time error.
Class properties are useful for sharing data across objects of a class or even between
classes. For example, in Chapter 5 we’ll study an ImageViewer class that creates a
rectangular region for displaying an image on screen. The ImageViewer class needs to
know which depths it should use when creating the movie clips that make up the
rectangular region. The depths are the same for every ImageViewer ...