Java Reference
In-Depth Information
Atthispoint,thechapterpresentsoneofJava'smoreconfusinglanguagefeatures:in-
terfaces.Youlearnwhatinterfacesare,howtheyrelatetoclasses,andwhatmakesthem
so useful.
Java programs create objects that occupy memory. To reduce the possibility of run-
ning out of memory, the Java Virtual Machine (JVM)'s garbage collector occasionally
performs garbage collection by locating objects that are no longer being used and re-
movingthisgarbagetofreeupmemory.
Chapter2
concludesbyintroducingyoutothe
garbage collection process.
Declaring Classes and Creating Objects
Structured programs create data structures that organize and store data items, and ma-
nipulatethedatastoredinthesedatastructuresviafunctionsandprocedures.Thefun-
damentalunitsofastructuredprogramareitsdatastructuresandthefunctionsorpro-
cedures that manipulate them. Although Java lets you create applications in a similar
fashion, this language is really about declaring classes and creating objects from these
classes. These program entities are the fundamental units of a Java program.
Thissectionfirstshowsyouhowtodeclareaclass,andthenshowsyouhowtocreate
objectsfromthisclasswiththehelpofthe
new
operatorandaconstructor.Thesection
thenshowsyouhowtospecifyconstructorparametersandlocalvariables.Finally,you
learn how to create arrays using the same
new
operator that's used to create an object
from a class.
Declaring Classes
A
class
is a template for manufacturing
objects
(named aggregates of code and data),
whicharealsoknownas
class instances
,or
instances
forshort.Classesgeneralizereal-
world entities, and objects are specific manifestations of these entities at the program
level.Youmightthinkofclassesascookiecuttersandobjectsasthecookiesthatcookie
cutters create.
Becauseyoucannotinstantiateobjectsfromaclassthatdoesnotexist,youmustfirst
declaretheclass.Thedeclarationconsistsofaheaderfollowedbyabody.Atminimum,
theheaderconsistsofreservedword
class
followedbyanamethatidentifiestheclass
(so that it can be referred to from elsewhere in the source code). The body starts with
anopenbracecharacter(
{
)andendswithaclosebrace(
}
).Sandwichedbetweenthese
delimiters are various kinds of declarations. Consider
Listing 2-1
.
Listing 2-1.
Declaring a skeletal
Image
class