| ★ wanayoo — archive 1999 http://developer.java.sun.com/developer/technicalArticles/DataTypes/storingobjects/ | Nouvelle recherche | Portail wanayoo |
|
|
|
In this article, Jacob Weintraub delves into storing data
in the JavaTM programming language and the various ways you can use that data. Specifically, he examines
how objects store data and how you can pass data to objects in method calls. He
also presents a discussion on encapsulation, a basic object-oriented design
strategy that helps you write better code.
In the previous column, I discussed Java programming as an interpreted language and
explained Java byte code and the JavaTM Virtual Machine1. You learned how to set up
Java on a system using the JavaTM 2 SDK, downloadable from Sun, and created your
first simple Java program. I then covered the basics of object-oriented
programming, and how it is centered around types and objects. Finally, I
introduced the class construct in the Java programming lanugage, and you created a class that looks like
this:
You also created a program (a class with a main method) that tests the
If you didn't read the last column, you'll probably want to review it before tackling this one.
Variables and Primitive TypesThough the snooze button is probably the most commonly used button on an alarm clock, the simpleAlarmClock class you've created so far is still
missing some important requirements. For instance, you have no way of
manipulating how long the alarm clock will stay in snooze mode. However, before
you can do that, you must take a more detailed look at how Java controls data.
Developers use variables in Java to hold data, with all variables having a data type and a name. The data type determines the values that a variable can hold. You will see in the examples below how integral types hold whole numbers, floating point types hold real numbers, and string types hold character strings. Called primitive types, integral and floating point are the simplest data types that Java uses. The following program illustrates the integral type, which can hold both positive and negative whole numbers. This program also illustrates comments, which document your code but don't affect the program in any way.
Java also uses floating point types, which can hold real numbers (numbers that include a decimal place). Here is an example program:
Try running the programs above. Remember, you have to compile them before you can run them:
Java uses four integral types and two floating point types, which both hold different ranges of numbers and take up varying amounts of storage space. The following table lists them, along with some of their properties:
A string type holds strings, and handles them differently from the way integral
and floating point types handle numbers. The Java language includes a
Variable ScopeIn addition to type, scope is also an important characteristic of a variable. Scope establishes when a variable is created and destroyed and where a developer can access the variable within a program. The place in your program where you declare the variable determines its scope.
So far, I've discussed local variables, which hold temporary data that
you use within a method. You declare local variables inside methods, and you can
access them only from within those methods. This means that you can retrieve
only local variables
You can declare local variables within any method. The example code below
declares a local variable in the
You can get to
Method ParametersA method parameter, which has a scope similar to a local variable, is another type of variable. Method parameters pass arguments into methods. When you declare the method, you specify its arguments in a parameter list. You pass the arguments when you call the method. Method parameters function similarly to local variables in that they lie within the scope of the method to which they are linked, and can be used throughout the method. However, unlike local variables, method parameters obtain a value from the caller when it calls a method. Here's a modification of the alarm clock that allows you to pass in thesnoozeInterval.
Member Variables--How Objects Store DataLocal variables are useful, but because they provide only temporary storage, their value is limited. Since their lifetimes span the length of the method in which they are declared, local variables compare to a notepad that appears every time you receive a telephone call, but disappears once you hang up the phone. That setup can be useful for jotting down notes, but you often want something a little more permanent. What's a programmer to do? Enter member variables.Member variables--of which there are two, instance and static--make up part of a class. I will consider instance variables now, and return to static variables in a later article. Developers implement instance variables to contain data useful to a class. An instance variable differs from a local variable in the nature of its scope and its lifetime. The entire class makes up the scope of an instance variable, not the method in which it was declared. In other words, developers can access instance variables anywhere in the class. In addition, the lifetime of an instance variable does not depend on any particular method of the class; that is, its lifetime is the lifetime of the instance that contains it. Remember instances from the previous article? Instances are the actual objects that you create from the blueprint you design in the class definition. You declare instance variables in the class definition, affecting each instance you create from the blueprint. Each instance contains those instance variables, and data held within the variables can vary from instance to instance.
Consider the
You can access instance variables almost anywhere within the class that declares them. To be technical about it, you declare the instance variable within the class scope, and you can retrieve it from almost anywhere within that scope. Practically speaking, you can access the variable anywhere between the first curly bracket that starts the class and the closing bracket. Since you also declare methods within the class scope, they too can access the instance variables. You can also access instance variables from outside the class, as long as an instance exists, and you have a variable that references the instance. To retrieve an instance variable through an instance, you use the dot operator together with the instance. That may not be the ideal way to access the variable, but for now, complete it this way for illustrative purposes:
Try this program out, and you'll see that Don't forget, the class definition is only a blueprint, so the instance variables don't actually exist until you create instances from the blueprint. Each instance of a class has its own copy of the instance variables, and the blueprint defines what those instance variables will be.
EncapsulationEncapsulation remains as one of the foundations of object-oriented programming. When using encapsulation, the user interacts with the type through the exposed behavior, not directly with the internal implementation. Through encapsulation, you hide the details of a type's implementation. In Java, encapsulation basically translates to this simple guideline: "Don't access your object's data directly; use its methods."
That is an elementary idea, but it eases our lives as programmers. Imagine, for
example, that you wanted to instruct a "person" object to stand up. Without
encapsulation, your commands could go something like this: "Well, I guess you'd
need to tighten this muscle here at the front of the leg, loosen this muscle
here at the back of the leg. Hmmm--need to bend at the waist too. Which
muscles spark that movement? Need to tighten these, loosen those. Whoops! Forgot
the other leg. Darn. Watch it--don't tip over ..." You get the idea. With
encapsulation, you would just need to invoke the Some advantages to encapsulation:
Here is a short example in which encapsulation clearly helps in a program's accuracy:
Even that simple program shows how you can slip into trouble if you directly
access the internal data of classes. The larger and more complex the program,
the more important encapsulation becomes. And remember, many programs start out
small and then grow to last indefinitely, so design them correctly, right from
the beginning. To apply encapsulation to
Before I proceed, I should discuss methods in more detail. Methods can return
values that the caller uses. To return a value, declare a nonvoid return type,
and use a
Write the ProgramOkay--you're ready to manipulate the snooze interval. You do this by adding get and set methods for the snooze interval. When you have an instance variable likesnoozeInterval, you will regularly call the get and set
methods getSnoozeInterval() and setSnoozeInterval().
Defined now are two methods to manipulate the snooze interval. One is used to
get the snooze interval, and the other is used to set it. That may seem
trivial, but then,
ConclusionYou've covered a great deal of new ground. You looked at how to manipulate primitive types likeint and double. You examined
local variables, method parameters, and variable scope. You learned how to add
data to classes using instance variables, and how that data is contained in each
instance. Finally, you explored encapsulation and how it leads to better code.
Next time, you'll see some more of the control structures in Java, such as
About the AuthorJacob Weintraub is founder and president of LearningPatterns.com (LPc). Jacob has been working in object technologies since 1989, and teaching Java since 1995. He authored LPc's "Java for Programmers", as well as many of its advanced courses, such as those on OOAD and EJB.
Reprinted with permission from the July 2000 edition of JavaWorld magazine. Copyright ITworld.com, Inc., an IDG Communications company. Register for editorial e-mailalerts
Reader FeedbackTell us what you think of this article.
_______ |
|||||||||||||||||||||||||||||||