Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

WHAT YOU’LL LEARN IN
THIS HOUR:
.Creating variables for an
object or class
.Using methods with
objects and classes
.Calling a method and
returning a value
.Creating constructors
.Sending arguments to a
method
.Usingthisto refer to an
object
.Creating new objects

As you learned during last hour’s introduction to object-oriented program-
ming (OOP), an object is a way of organizing a program so that it has every-
thing it needs to accomplish a task. Objects consist of attributes and behavior.


Attributesare the information stored within an object. They can be variables
such as integers, characters, and Boolean values, or objects such as String
and Calendarobjects. Behavioris the groups of statements used to handle
specific jobs within the object. Each of these groups is called amethod.


Up to this point, you have been working with methods and variables of
objects without knowing it. Any time your statement had a period in it
that wasn’t a decimal point or part of a string, an object was involved.


Creating Variables


In this hour, you are looking at a class of objects called Viruswhose sole
purpose in life is to reproduce in as many places as possible—much like
some people I knew in college. AVirushas severaldifferent things it needs
to do its work, and these are implemented as the behavior of the class. The
information that’s needed for the methods are stored as attributes.


The attributes of an object represent variables needed for the object to func-
tion. These variables could be simple data types such as integers, charac-
ters, and floating-point numbers, or they could be arrays or objects of
classes such as Stringor Calendar. You can use an object’s variables
throughout its class, in any of the methods the object contains. By conven-
tion, you create variables immediately after the classstatement that cre-
ates the class and before any methods.


HOUR 11


Describing What Your


Object Is Like

Free download pdf