1. Trang chủ
  2. » Công Nghệ Thông Tin

head first java second edition phần 2 ppt

68 481 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 68
Dung lượng 3,59 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

class object class object, method class, object instance variable object, class method, instance variable object class object, instance variable class object, instance variable Pool Puzz

Trang 1

bang bang ba-bang

ding ding da-ding

class DrumKit {

boolean topHat = true;

boolean snare = true;

void playTape() { System.out.println(“tape playing”); }

void recordTape() { System.out.println(“tape recording”); }

}

class TapeDeckTestDrive { public static void main(String [] args) {

TapeDeck t = new TapeDeck( );

t.canRecord = true;

t.playTape();

if (t.canRecord == true) { t.recordTape();

} } We’ve got the template, now we have

} to make an object !

class DVDPlayer { boolean canRecord = false;

void recordDVD() { System.out.println(“DVD recording”); }

void playDVD ( ) { System.out.println(“DVD playing”);

}

}

class DVDPlayerTestDrive { public static void main(String [] args) { DVDPlayer d = new DVDPlayer();

d.canRecord = true;

d.playDVD();

if (d.canRecord == true) { d.recordDVD();

} } The line: d.playDVD( ); wouldn’t

} compile without a method !

%XERCISE

1dQ^OU_Q

Be the Compiler:

Trang 2

you are here4

classes and objects

47

public class EchoTestDrive {

public static void main(String [] args) {

Echo e1 = new Echo();

Echo e2 = new Echo( ); // the correct answer

I am compiled from a java file.

My instance variable values can be different from my buddy’s values.

I behave like a template.

I live on the heap.

I am used to create object instances.

My state can change.

I declare methods.

I can change at runtime.

class

object class object, method class, object instance variable object, class method, instance variable object

class object, instance variable class

object, instance variable

Pool Puzzle

7HO

Note: both classes and objects are said to have state and behavior They’re defined in the class, but the object is also said to ‘have’ them Right now, we don’t care where they technically live.

0UZZLE

Trang 3

Know Your Variables

Variables come in two flavors: primitive and reference. Sofaryou've used variables In two places-as object state (instance variables), and as local variables

(variables declared within a method).Later, we'll use variables as arguments (values sent to a method by the calling code), and as return types (values sent back to the caller of the method) You've seen variables declared as simpie prj m IUve integer vaIues (type in c) You've seen variables declared as something more complex like a String or an array But there's gotta be more to life than integers, Strings, and arrays.What If you have a PetOwner object with a Dog instance variable? Or aCarwith an Engine? In this chapter we'll unwrap the mysteries of Java

types and look at what you can declare as a variable,what you can pur In a variable, and what you

cando with a variable And we'll finally see what life Is truly like on the garbage-collectible heap.

this Is a new chapter 49

Trang 4

declaring a variable

Peclarittg avariable

Java cares abouttype Itwon't let you dosomething bizarre and dangerous like stuff aGiraffe reference into a Rabbit variable-whathappens when someone tries to ask the so-called

Rabbitto hop ()? And it won't let you put afloating point number into an integer variable,unless you lKknowledge to the compiler that you

know you might lose precision (like, everythingafter the decimal point)

The compiler can spot most problems:

Rabbit hopper =new Giraffe();

Don't expect that to compile Thankfully

For allthis type-safety to work, you must declarethe type of your variable Isit an integer? a Dog?

A single character? Variables come in two flavors:

primitiveandobjectreference. Primitives holdfundamental values (think: simple bit patterns)including integers, booleans, and floating pointnumbers.Object references hold well, references

toobjects (gee, didn't that clear it up.)

We'Ulook at primitives first and then move

ontowhat an object reference really means.But regardless of the type, you must foUow twodeclaration rules:

variables must have a typeBesides a type, a variable needs a name, so thatyou can use that name in code

variables must have a name

Note: When you see a statement like: "an object

of type X", think of l)'Peand classessynonyms

(We'll refine that a little more in later chapters.)

Trang 5

Primitive Types

Integer

byte 8bits -128 to127short 16bits -32768to

32767int 32bits -2147483648

to2147483647long 64bits -huge to huge

Type BitDepth ValueRange

boolean and char

boolean (JVM pedfic)true or false

aci~\e, "",\65'fO'#

Primitive declarations with assignments:

'!II" And inJava, primitives come in different sizes, and those sizes

have names When you declare a variableinJava,

IE ::a-YoU must declare it with a specific type Thefour containers here are for the four

integer primitives in Java

cup holds a value, so for Java primitives, rather than saying, "I'd like a

french roast", yousayto the compiler, "I'd like an int variable with the

ber 90 please." Except for one tiny difference in Java you also have to

your cup a name So it's actually, "I'd like an int please, with the value

:H86,and name the variable height."Each primitive variable has a fixed

ber of bits (cup size) The sizes for the six numeric primitives inJava

shown below:

n you think ofJava variables, think of cups Coffee cups, tea cups, giant

that hold lots and lots of beer, those big cups the popcorn comes in at

movies, cups with curvy, sexy handles, and cups with metallictrimthat

lea r nedcannever, evergo in the microwave

wariableisjusta cup Acontainer It holdssomething

a size, and a type Inthis chapter, we're going to look first at the

- bles (cups) that hold primitives, then a little later we'll look at cups

hold references to objects Stay with us here on the whole cup analogy-as

pie as it is right now, it'll give us a common way to look at things when

discussion gets more complex And that'll happen soon

- itives are like the cups they have at the coffeehouse.Ifyou've been to a

ucks, you know what we're talking about here They come in different

and each has a name like 'short','tall', and, "I'd like a

de' mocha half-eaffwith extra whipped cream"

migh t see the cups displayed on the counter,

ucan order appropriately:

you are here ~ 51

Trang 6

prlmltlve assignment

You really dot1~t wat1t to spill that

Be sure the value can fit into the variable

You can'tputa large value into asmall cup

WeU, OK,you can, but you'lllose some You'll get, as wesay,

spillage. Thecompiler triesto

help prevent this ifit can tellfrom your code that something'snot going to fit in the container(variable/cup) you're using

For example, you can't pour anint-full of stuffinto a byte-sizedcontainer,asfollows:

int x = 24;

byte b = x;

//won't work!!

Whydoesn'tthis work, you ask? After all, the value ofxis24, and 24 is definitely

small enough to fit into a byte.You know that, and weknow that, but all the

compiler cares about is that you're trying to put a big thing into a small thing

and there's thepossibilityof spilling.Don'texpect the compilertoknow what the

value of xis evenif youhappen tobe able tosee it literally in your code

You canassigna value to a variableinone of severalwaysincluding:

• type a litera/value after the equalssign(x=12 isGood =true,etc.)

• assign the value of one variable to another (x=y)

• use an expression combining the two (x=y+43)

In the examples below, the literal values arein bolditalics:

The compiler won't let you put

a value from a large cup into

a small one But what about the other way-pouring a small cup intoabig one7 No problem.

Basedon what you know about the size and type of the pri mitive varlables,see if you can figure out which of these are legal and which aren't,

We haven't covered all the rules yet, so on some of these you'll have to use your best

judgment Tip: The compiler

always errs on the sideofsafety.

From the following listCircle

the statements that would be legal if these lines were ina

declare a double namedd,assign it the value456 709

declare a boolean named IsCrazy (no assignment) assign the value true to thepreviously-declared ;sCrazy declare an int named y, assign Itlhe value thatisthe sum

of whateverxis now plus 456

true;

isCrazy

char initial = ' j ' ;

Trang 7

Jack away frotH that keyword!

lbu know you need a name and a type for your variables

YOualready know the primitive types

, whatcanyou we as names? The rules are simple You

an namea class,method, or variable according to the

owing rules (the real rules are slightly more flexible,

tthesewillkeep you safe):

dollar algn($).You can't atart a name with a

number

well Just don't atart It with a number,

rules,JU8t 80long as It Isn't one of Java's reserved

words

' ftIfIeSote: b\e

, /'ItprimitIve '7" float doU

Theelg e s\"lOftlot long t/'lem:

\eao char byt membermg

, omnem

S u\dn't nCafefU\~ 8ea's \"10

public

fhls table reserved.

doss ex1and~ implements import rnstanceof interface new package super this

boolean char byte short int long floa.t double

tthere are a lot more we haven'tdiscussed yet Even ifyou don't

edtoknow whatthey mean, you still needtoknow you can'tuse

'em yourself.Do not-under any circumstances-try tomemorizethese

.w.To make room for these in your head, you'd probably have to

something else.Like where your car is parked Don'tworry, by

the end of the book you'll have most of them down cold

you are here 53

Trang 8

object references

Controlling your ~og object

You know how to declare a primitive variable and assignita

value.But now what about non-primitive variables? In other

words, what about objects?

• There Is actually no such thing as anobjectvariable

• There's only an objectreferencevariable

• An object reference variable holds bits that represent a

waytoaccess an object

• It doesn't hold the object Itsetf, but It holds something

like a pointer Or an address Except., in Java we don't

really knowwhat Is Inside a reference variable.We do

know that whatever It Is, It represents one and only one

object And the JVM knows howtouse the referenceto

gettothe object

You can' 1stuff an object into a variable We often think of

it thatway. we say things like, "I passed the String to the

System.out.printlnf) method." Or, "The method returns a Dog",

or, "I put a new Foo object into the variable namedrnyf'oo."

But that's not what happens There aren't giant

expandable cups that can grow to the size of any

object Objects live in one place and one place

only-the garbage collectible heap! (You'll

learn more about that later in this chapter)

Although a primitive variable is full of

bits representing the actual valueof the

variable, an object reference variableisfull

of bits representingawaytogetto the

obJect.

You use the dot operator (.)

on a reference variable10say,

"use the thingbefore the dot to

get me the thingafterthe dot." For

example:

myDog.bark() ;

means,"use the object referenced by the variable myDog to

invoke thebarkt) method." When you use the dot operator on

an object reference variable, think of it like pressing a button

on the remote control for that object

Trang 9

byte short int

8 16 32

long reference

64 Ibll depth not relevant)

The 3 steps of object declaration, creation and assignment

~3~

At1 object referet1ce is just

variable myDog The reference variable

Is , forever of type Dog ln other words,

a remote control that has buttons to controlaDog, butnota Cat or a Button

oraSocket.

Dog

Dog myDog = new Dog () ;

Assigns the new Dog to the reference variable myDog.ln other words,

programs the remote control,

and the reference

Dog myDog '" new Dog () ;Tells the JVM to allocate space for a new Dog object on the heap (we 'll

learn a lot more about that process, especially in chapter 9,)

~\.\

vall.4t

byte

Dog myDog = new Doq() ;

Something that goes In a cup

Only this time, the value 15 a remote control

Prhldtlve Variable

byte x = 7;

thebits representing7go

to the variable (00000111),

~n care how meny t' s and O's tho,o are In a (afare~08l1tlriabla lrs UP10a&eh

: " a."ld Ihe phase of Ihe moon,

you are he re 55

Trang 10

A.:Vou don't know Unless

you're cozy with someone on the

JVM's development team, you

don't know how a reference is

represented There are pointers

in there somewhere, but you

can't access them.You won't

need to.(OK,IfyouInslst,you

might as well Just imagine It

to be a 54-bit value.) But when

you're talking about memory

allocation issues, your Big

Concern should be about how

manyobjects(as oppose-d to

objectreferences) you're creating,

and how bigthey(theobjects)

really are

Q:So, doesthat meanthat

all objectreferences arethe

same size, regardless ofthesize

oftheactuaI objects to which

theyrefer?

A.:Yep All references for a

given NM will be the same

size regardless of the objects

they reference, but each JVM

might have a different way of

representing references, so

references on one JVM may be

smaller or larger than references

on another JVM

Q:canI do arithmetic on a

reference variable, IncrementIt

you know - C stuff7

A.:Nope Say It with me again,

Reference:Pretty simple, really I'm a remote control and Icanbe programmed tocontrol different objects

HeadArstDo you mean different objectsevenwhile you'rerunning?Like, canyourefer to a Dog and thenfive minutes later refer to a Car?

Reference: orcoursenot-OnceI'm declared,that'sit.IfI'maDog remote controlthenrunever be able to point (oops- my bad, we're not supposed to saypoin~I meanrifer

to anything but a Dog

HeadFirstDoes that mean youcanrefer to only one Dog?

Reference:No.Icanbereferring to one Dog, and thenfiveminutes later Icanrefer tosomeother Dog.Aslongasit's a Dog,Icanbe redirected (like reprogranuning your remote

toadifferent TV) to it Unless no never mind

HeadFirstNo, tell me What were yougonnasay?

Reference:I don'tthink you wanttoget intothisnow,butI'lljustgiveyou the shortversion - ifI'mmanedas final,then onceIam assigneda Dog,Ican neverberepro-

grammed toanything elsebutI1ul1one and only Dog:Inother words, no other objectcan

be assigned to me

HeadFirstYou'reright,wedon'twant totalkabout that now.OK, so unlessyou're

final,then you can refer to one Dog and then referto a differentDog later.Canyou everrefertofIl)tJringat alP.Isit possibleto not be programmedtoanything?

Reference:Yes, but itdisturbsmetotalkaboutit

HeadArstWhy is that?

Reference:Because it means I'mnull,and that's upsettingto me

HeadFirstYou mean.becausethen you have no value?

Reference:Oh, null isa value.I'mstilla remote control, but it's like you broughthome a newuniversalremote control and you don't have a TV I'm not programmed tocontrolanything Theycanpressmybuttonsallday long, but nothinggoodhappens.Ijust feelso useless Awaste ofbits.Granted, not that many bits, butstill.And that's notthe worst part.IfIamthe only reference to a panicular object, and then I'm set tonull

(deprogrammed), it means that nowrwboqycanget to that object I had been referring to

HeadFirstAnd that's badbecause

Reference:You have toask?Here I've developed a relationship withthisobject, anintimate connection,and then the tieissuddenly, cruelly, severed.And Iwillnever seethat objectagain,because now it's eligiblefor [producer, cue.tragicmusic)garbage collection.

Sniff But do you think programmers ever consider!haP.Snif.Why,wIrYcan't Ibea primi

-tive?I hate being a refcrcut. The responsibility, all the broken attachments

Trang 11

ott the garbage collectible heap

= new Book();

= new Book();

e two Book reference

- l es.Create two new Book

Assig n the Book objects to

re a new Book reference var iable.

r than creating a new, third Book

•assign the value of variable c to

bled But what does th is mean?

li e saying, "Take the bits I nc,make a

of them , and stick that copy Intod."

c and d refer to the same

ect.

.me value Two remotes

grammed to one TV.

f erences:3

Objects:2

c = h;

As sign the value of variablebto

va riab lec.Bynow you know what

i s means The bits inside variable

atare copied , and that new copy Is

stuffed into variablec

Both band c refer to the

Trang 12

objects on the heap

Ufe a.,d death 0., the heap

Declare two Book reference variables.

Create two new Book objects Assign

the Book objects to the reference

Assign the value of variable c to variableb

The bits Inside variable c are copied, and

that new copy is stuffed Into variableb.

Both variables hold identical values.

Both band c refer to the ••me

object Object 1 I abandoned

and eligible for Garbage

Collec-tion (GC)

Active References: 2

Reachable Objects: 1

Abandoned Objects: 1

The first object thatbreferenced, Object 1,

has no more references It's unreachable.

Assign the value nu 11 to variable c.

This makes c a null reference, meaning

It doesn't refer to anything But It's still

a reference variable, and another Book

object canstilibe assigned to It

Object 2 tlll h •• an active

reference (b), and •• long

as It does, the object I not

Trang 13

An array is like atray of cups

o Declarean int array verinble Anarray variable is

a remote control to an array object

int[] nums;

Create anew int array w ith a length

of 7Iandassign it to the declared intrJvariable nums

previously-nums =new int[7] ;

Give each element inthe array

anint value

Remember, elements inon int

arrayare just int variables

int array object (int[])

Not it~ that -tne a'rYa'f ihtlt isdl'l objtd:,evel'lt.h~h ~e I tltMtl'lt.s art f\"i",j·I:.'Ives

Arrays are objects too

Java standard library includes

of sophisticated data structures

uding maps, trees and sets

AppendixB).but arrays are

twhen you just want a quick

red, efficient list of things

,"'5give you fast random

ess by letting you use an index

ition to getto any element in

array

ryelement in an array isjust

nriable.In other words, one of

eight primitive variable types

k: Large Furry Dog) or a

reference variable.Anything youwould put in avariableof that rypecanbeassigned to an array element

of that type So in an array of type

int (int[]).each element can hold

an int,Ina Dog array (Dog[]) eachelement can hold a Dog? No

remember that a reference variablejust holds a reference (a remotecontrol), not the object itself.So

in a Dog array, each element canhold aremote controlto a Dog Ofcourse, we still have to make theDog objects and you'll see all that

on the next page

Be sure to notice onekeything

in the picture above - the arm)' is

an object, even though it's an array of primitives.

Arraysarealways objects, whetherthey're declared to bold primitives

or object references But you canhave an array object that's declared

to holdprimitive values In otherwords, the array object can have

elementswhich are primitives butthe array itself isnevera primitive,

Regardless of what the array holds,the array itself is always an objectl

you are here. 59

Trang 14

an array of objects

Make att array of Pogs

pets = new D09[7];

pets[D] = new Dog();

pets[l] = new Dog();

A Create a new Dog array with

W a length of 7, and assign it to

the previously-declaredDog[J

variablepets

Dog array object (Dog[])

Dog array object (Dog[])

Declare a Dog array variable

Dog[] pets;

o

What~ .ttfsShtg1

Dogsl We have an array

of Dogrmrence$,but no

actual DogobJectsI

A Create new Dog objects, and

V assign them to the array

elements

Remember, elements in a Dog

arrayare just Dog reference

variables. We still need Dogs!

Trang 15

Java cares about type.

Once you've declared an array you

can't put anything an It except

thing-thatareofthedeclared array type

For example,youcan'tputQCOt into a Dog

array (it would beprettyawful if someone

thinks that only Dogs are inthe orrat, so

the.yask eoch one to ~ark, and th~n to their

horror discoverthere s a cat lurkmg.) And

youcan't sticka double intoonint orr'atl

(spillage.,remember?) You can,however.

put Qbyte into on int arraf, b~QuSe a

byte will always fit intoonint-SIZed

cup

This is known as an Implicit wid&ning We'''

gat Into the details tater for now just

rememberthat the compiler won't 1styou

put the wrM'9 thing In onorraf, based on

the Gtf'OY's d&eloredtype

namebarkOeatO

chaseCalO

Cot1trol your ~og

(with a referetlce variable)

Dog fide = new Dog();

fido.name = ~FidoN;

We created a Dog object andused the dot operator on thereference variablefidoto accessthe name variable."

We can use thefido reference

to get the dog to barkt) oreat/) or chaseCatO

When the Dog is in an array,we don'thave an actual variable name (like

fido). Instead we use array notation andpush the remote control button (dot

~perator)on an object at a particularIndex (position) in the array:

Dog[] myDogs = new Dog[3];

myDogs[O] =new Dog() ;myDogs[O].name = "Fido";

myDogs[O] bark();

-trying tokeep it simple For now W '1Igdencapsu. e iatiOn he _reo but we 're

0 encapsulation 10 chapter 4.

you are here ~ 61

Trang 16

using references

class Dog (

String name;

publi c static void main (String() args)

II make a Dog object and ac cess it

Dog dogl = new Dog();

• Areference variable is like a remote control.Using the dot operator (.) on a referencevariable islike pressinga button on the remole

control to access a method orinstance variable

• Areference variable has a value ofn u 11when

itis not referencing any object

• Anarray is always an object,evenifthe" arrayisdeclaredtohold primitives" Thereis no suchthing as a primitive array,only an array that

holds primitives

"Fr e d " ;

"Marge" ;

ne w Dog () ;new Dog ();

pUblic void bark() (

System.out.println(narne i- " says Ruff!");

II Hmmnm what is myDogs(2j name?

System.out.print( "!ast dog's name is ");

Sys t em ou t.p r in t l n (myDogs (2).narne ) ;

int x = 0;

whi1e(x < mYDOgs 1ength)~ J

myDogs [xl ba r k (); a \/aYiab\cl'~~

x = X + 1; ay-yii'(Sha\/C t."c l'I~bCl"

t)lat.~\\/ts 'lOlA a'J

L ' t,\lcjlY"Y I

e\e,.,.tf\'V11'1

62 chapter 3

Trang 17

BE the cornriler

detel"llline whether each of these files

myBooks{Oj.title :: "The Grapes of Java";

myBooks(lj.title = ~The Java Gatsby"i

myBooks(2).title :: ~The Java Cookbook";

Trang 18

exercise: Code Magnets

AworkingJavaprogramIs all scrambled up

on the fridge Can you reconstruct the codesnippets to make a working Java programthat produces the output listed below?

Some of the curly braces fell on the floorand they were too small to pick up, so feelfree to add as many of those as you need!

int Y==

int ref;

index(y) ;

while (y < 4) {System.out.print1n(islands{refj)i

Trang 19

int height;

iot length;

public static

pool puzzle

YourJob is to take code snippets from

the pool and place them into the blank lines in the code You may use the same snippet more than once, and you won't need to use

allthe snippets YourgOlllis to make a class thatwillcompile and run and produce the output listed.

I area"};System.out.println(" = " + area):

For extra bonus points, use snippets

from the pool tofillin the missing

Note: Eachlnlppetfromthepoolnn beused morethanoncel

Trang 20

puzzle: Heap o' Trouble

A Heap 0' Trouble

A short Java program is listed to the

right When'/1do stuff' is reached, some

objects and some reference variables

will have been created Your task Is

to determine which of the reference

variables refer to which objects Not all

th e reference variables will be used, and

some objects might be referred to more

than once Draw lines connect ing the

reference variables with their matching

objects

Tip: Unless you're way smarter than us,

you probably need to draw diagrams

like the ones on page 55 and 56 of th is

chapter Use a pencil so you can draw

and then erase reference li nks ( the

arrows goIng from a reference remote

hq(x] id == Xi

x = X + 1i

}

hq[3] == hq[l]i hq[4] hq[l] ; hq[3] = null;

hq (4) hq (0] ; hq(Ol == hq(31i hq(3] hq[2];

Trang 21

The case of the pilfered references

Itwasaclarkandstormy night Tawny strolled into the programmers' bullpen like sheowned the place She knew that all the programmers wouldstill behard at work, and shewanted help She needed a new method added to the pivotal class that was to be loaded intothe

client's new top-secretJava-enabledcell phone Heapspaceinthe cell phone's memorywas

as tight as Tawny's top, and everyone knew it The normally raucous buzzinthe bullpen fell tosilence as Tawnyeasedher way to the white board Shesketcheda quick overview of the newmethod's functionality and slowly scanned theroom 'Wellboys, it's cnmch time", shepurred

'Whoever creates the most memory efficientversion ofthis methodiscoming with me to theclient's launchpartyon Maui tomorrow to help meinstallthe new software."

The next morning Tawny glided into the bullpen wearing her short Aloha dress

"Gentlemen",she smiled, "the plane leaves in afewhours, show me what you'vegot!" Bob wentfirst;as he began to sketchhisdesignon the whiteboardTawnysaid, "Let's gettothe point Bob, show me how you handledupdatingthe list of con-

tactobjects." Bobquickly drewacodefragmenton the board:

Contact I) ca = new Contact[10];

while ( x < 10 ) { II make 10 contact objects

x = x + 1 ;

II do complicated Contact list updating stuff with ca

"Tawnyrknow we're tight on memory,but yourspecsaid that wehadtobeable toaccessindividualcontact informationfor all ten allowablecontacts,thiswas the best scheme I could

cookup",said Bob Kent was next, alreadyimaginingcoconutcocktailswith Tawny,"Bob,"

he said, "your solution'sa bit kludgy don't you think?"Kent smirked,"Take a look atthis

baby":

Contact refc;

while ( x < 10 ) { II make 10 contact objects

refe = new Cont.act()i

x = x + 1;

I

II do complicated Contact list updating stuff with rete

"Isaved a bunch of reference variables worth ofmemory, Bob-o-rino,so put away yoursunscreen", mocked Kent "Not so fast Kent!", said Tawny,"you've saved a little memory, butBob'scoming with me.''

Why did Tawny choose Bob's method over Kent's, when Kent's usedJessmemory?

Trang 22

exercise solutions

Exercise Solutions class Books {String title;

String autbor;

)if(z==2){

public static void main{String I) args) {Hobbits () h = ne_w= H :.ob:: :b7i: :t :.s~(3: :)~: ~, , -,

Int:z ::-1; IRemember: o.rrcys start with

int x =0:

myBooks[O] ::ntw 9ooksO; IUrnanber: We hGvtto

myBooks[1] ::ntw BooksO: actuclilyInQJc.etheBooI<s

myBooks[2] ::newBooksO: ~~ =-objectsI l

myBooksIO].title = uThe Grapes of Java';myBooksll].title ="The Java Gatsby·;

myBooks[2].title =NThe Java Cookbook';myBooks[O].author = Nbob';

myBooks[l].author =Nsue";

myBooks[2].author = "ian";

while (x < 3) {System.out.print(myBoOks(x).title)iSystem.out.print(" by ")j

system.out.println(myBooks[x).author);

x e X +1;

A Code Magnets:

}

}

class TestArrays

pUblic static void main(String () args) {

int [) index = new int{4]:

Trang 23

but the last of the Contact objects that his method ated.With each trip through the loop, he was assign-

cre-ing a new object to the one reference variable,so thepreviously referenced object was abandonedontheheap - unreachable.Without access to nine of the tenobjects created, Kent's methodwasuseless

(The softwarewas8 huge success atKl the dlentgaveTawny and Bob anextra week

Syatem.out.pr int(Ny = U + Y);

System out.println(", tS area " U+ tS.area);

Trang 24

4 methods use Instance variables

How Objects Behave

State affects behavior, behavior affects state. We know that objects have state and behavior, represented byInstancevariables and methods But until now, we

haven't looked at how state and behavior are related We already know that each instance of a class (each object of a particular type) can have its own unique values for its instance variables.

Dog A can have a name "Fido" and a weight of 70 pounds Dog B Is"Killer" and weighs 9 pounds And If the Dog class has a method makeNoiseO,well , don't you think a 70-pound dog barks a bit deeper than the little 9-pounder7 (Assuming that annoying ylppy sound can be considered

a bark.) Fortunately, that's the whole point of an object-It has behavior that acts on its state In other words,methods use /nstllnn vllt/llb/Ift values Like,"if dog Is less than 14 pounds, make ylppy sound, else " or "Increase weight by 5~ Let's go chllnge some stat«,

this Is a new chap ter 71

Trang 25

RetMetMber: a class describes what an

object knows and what at1 object does

C-illi~ playO 0l'I this iflSta~te

will t4lASe"My W;Y:: to play.

(blAt PI~ the ~r.ab-a ~d

Song

title

artist

setTItleOsetArtlstOplayO

lt1stat1ce variables

(state)

'Methods

(behavior)

A classisthe blueprint for an object When you

write a class, you're describing how theJVM

should make an object of that type You already

know that every object of that type can have

differentinstance variablevalues But what about

Well sortcif.*

Every instance of a particular class has the same

methods, but the methods can behavedifferently

based on the value of the instance variables

The Song class has two instance variables, title

and artist.The playO method plays a song but

the instance you call playO on will play the song

represented by the value of thetitleinstance

variable for that instance So,ifyou call the playO

method on one instance you'll hear the song

"Politik", while another instance plays"Darkstar",

The method code, however, is the same

Trang 26

methods use instance variables

System.out.println("Yip! Yip!-);

~ : = s s DogTestDrive {

Dogsize

p b li c static void main (String!J args) {

Dog one = new Dog();

one.size = 70;

Dog two = new Dog();

two,size = 8;

;;:=':' ng name;

AtlD3cIJDog's bark is different from a big Dog'sbark

og class has an instance variablesize,that the

meth od uses to decide what kind of bark sound

Dog three = new Dog();

Trang 27

You can send things to a tttethod

Just as you expect from anyprogramming language,youaU1passvalues into

your methods You might, for example, want to tell a Dog object how many

times to bark bycalling:

d.bark(3) ;

Depending on your programming background and personal preferences,

youmight use the termargumentsor perhapsparamet.ersfor the values passed

intoa method.Although thereemformal computer science distinctions that

people who wear lab coats and whowill almost certainly not readthisbook

make we have bigger fish tofryinthis book Soyuucan callthem whatever

you like (arguments,donuts, hairballs, etc.) but we're doing it like this:

A method ~parameters A caller passes arguments.

Arguments are the things you pass into the methods Anargument (a value

like 2,"Faa", or a reference to a Dog) lands face-down into a wait for it

parameter.And a parameter is nothing morethana local variable A variable

witha type and a name, that can be used inside the body of the method

But here's the"important part:Ifa method takes a parameter, you mustpass

it something And that something mustbea value of the appropriate type

O Call the bark method on the Dog

refer-ence, and pass in the value 3(as the

argument to the method)

d.bark(3) ;

~ aY'~~",e~t.

A The bits representing the int

W value 3 are delivered into thebark method

System.out.println("ruff");

A The bits land in the numOfBarks

V parameter (an int-stzec variable)

}

}

74 chapter 4

Trang 28

methods use instance variables

ods can return values Every methodisdeclared with a return

but until now we've made all of our methods with a void

type,which means they don't give anything back

recandeclareamethodtogiveaspecific typeof value

to the caller, such as:

~ giveSecret ()

return 42;

declare a method to return a value, you must

a value of the declaredrypel (Or a value

(()mpatiblewith the declared type We'll get

at morewhen we talk about polymorphism

pte r7and chapter 8.)

atever you say

'II give back, you

tter give back!

ill aWl \WI\

you are here ~ 75

Trang 29

arguments of the right type and order.

Call1"Q a two-paralMeter IMethod, altd seltdh,g

Trang 30

methods use instance variables

goes into the variable named x.

void go(int z){ }~int A Declare a method with an int

f t Call the goO method, passing

W the variable x as the argument The bits in x are copied, and the copy lands in z

A Change the value of z inside

V the method The value of x doesn't change! The argument passed to the z parameter was only a copy of x.

-The method can't change the bits that were in the calling variable x.

Trang 31

Reminder: Java cares about type!

You can't return a Giraffe whenthe return type Is declared

as aRabbit Same thing withparameters You can't pass aGiraffe Into a method thattakes a Rabbit

• Classes definewhat anobject knows andwhalanobject does

• Things an object knows are itsInstancevariables(state)

• Things an object does areitsmethods (behavior)

• Methods can use instance variables so that objects

of the same type can behave differently

• Amethod can have parameters, which means youcan pass one ormore values in to the method

• The number and type ofvalues you pass inmustmatch the order and type of the parametersdeclared bythe method

• Values passed in and out ofmethods can beimplicitly promoted to a largerIypeorexplicitly cast

toa smaller type

• The value you pass as an argument to a methodcanbea literal value (2,'c',etc.) ora variable ofthe declared parameter type (for example, x where

xis an intvariable).(There are other things youcan pass as arguments, but we're not there yet.)

• Amethodmustdeclare a retum type.Avoid retumtype means the method doesn't return anything

• Ifa method declares a non-void return type,itmust

return a value compatible with the declared return

type.

Q :Do I havetodo something with the return

value of a method? can IJust Ignore it?

A:Java doesn't require you to acknowledgea

return value You might want to call a method with

anon-void return type, even though you don't care

about the return value In this case, you're calling

the meth od for the work it does inside the method,

rather than for what the method gives returns In

Java, you don't have to assign or use the return value.

Q:What happens Ifthe argumentyouwant to

pass Is an object InsteadofIIprimitive?

A:You'll learn more about this In later chapters,

but you already know the answer Java passes

everything by value EverythIng But value means

bits Inside the vcrtable.And remem ber,you don't

stuff objects Into variables; the variable Is a remote

control-a reference to an object So If you pass a

reference toanobject intoamethod, you're passing

a copy of the remote control Stay tuned, though, we'll

have lots more to say about this.

Q :Can a method declare multiple return values?

Or Is there some way to return more than one

value?

A:Sort of Amethod can dec lare on Iy one return

value.BUT If you want to return, say, three int values,

then the declared return type can be an Int orray.

Stuff those lnts into the array,and pass It on back It's

alittle more involved to return multiple values with

different types; we'll be talking about that in a later

chapter when ~e talk about ArrayLlst.

' Q :Do I havetoreturn the exact type , declared?

A.:You can return anything that can be implicitly

promoted to that type So, you can pass a byte where

an Int Is expected The caller won't care,because the

byte fits Just fine Into the tnt the caller will use for

assigning the result You must use an explicit cast

when the declared type Is smaller than what you're

trying to return.

78 chapter 4

Trang 32

methods use instance variables

brand

numOfPickupsrockStarUsesl1

getBrandOselBrandOgetNumOfPickuPSOsetNumOfPickupsOgetRockStarUsesltOsetRockSlarUsesllO

_ _ .e 've seen how parameters and return types work, it's

them to good use: Getters and Setters.Ifyou're into

rmal about it, you might prefer tocallthemACC610TS

.Jw.;ifO;OOI rl.But that's a waste of perfectly good syllables

Gc ters and Settersfitsthe java naming convention so

~,wl:l2 lwe'Ilcall them

nd Setters let you, well,get andsathings.Instance

van-1r:1_ JeS.usually A Getter's sole purpose in lifeisto send back,

~az!lnlvalue, the value of whatever itis that particular Getter

".-a s.:dto be Getting And by now, it's probably no surprise

1&3, ~nerlives and breathes for the chancetotake an

argu-.~1Deand use it to setthe value of an instance variable

youare he re 79

Trang 33

00 It or risk hUlMlliatiot' at'd

ridicule.

Until this most important moment, we've

been committing one of the worst 00

faux pas (and we're not talking minor

violation like showing up without the IB'

in BYOB) No, we're talking Faux Pas with

a capital 'F'.And ·P'

Our shameful transgression?

Exposing our datal

Here we are.just humming along without

a care in the world leaving our data out

You may have already experienced that

vaguely unsettling feeling that comes with

leaving your instance variables exposed

operator, as in:

theCat.height : 27;

control to make a direct change to the Cat

object's size instance variable In the hands

of the wrong person, a reference variable

(remote control) is quite a dangerous

weapon Because what's to prevent:

't.

theCa t height = 0; 1e-t ~i5 "ayYt".

This would be a Bad Thing We need to

80 chapter 4

public void setBeight (int ht) {

if (ht > 9) {height: ht;

}

Trang 34

itisthat simple to go from

implementation that's just

g for bad data toone

protects your data and

ects your right to modify

imp leme nta tion later

so how exactly do you

the data? With the

lie and private

ess modifiers.You're

iarwith public-we use

rithevery main method

re's an encapsulation

nile of thumb (all

stan-disclaimers about rules

~thumb are in effect): mark

instance variablesprivati!

providepublicgetters

setters for access control

you have more design

codi ng savvyin Java, you

bably do things a little

re ntly, but for now this

I!!!IlP:oachwillkeep you safe

ark getters and

etters pUblic.

·Sodly Bill forgot to

CftCopsulQt~ his Cat class and

ended up wltkQ flat cat.H

(overheard at the watercooler)

methods use Instance variables'"

Java'~edThis week's Interview:

An Object gets candid about encapsulation.HeadFirstWhat's the big deal about encapsulation?

Object:OK., you know thatdreamwhere you'regivingatalk to500people when yousuddenlyrealize-you'reTUJkaP.

HeadFirst:Yeah, we've had that one It's right up there with the one about the Natesmachine and no,wewon't go there OK, so you feel naked.But otherthan being a littleexposed,is thereanydanger?

ObjectIsthereanydanger?Isthere any danger?[St3.I'1Slaughing]Hey,didallyou other

instances hear that, "Is lhert aT[! danger?"heasks?[falls on the floor laughing]

HeadFirst:What's funny about that? Seemslikea reasonable question

Object:OK,I'llexplain it It's[bW'StSout laughing again, uncontrollably]

HeadFirst:CanIget you anything? Water?

Object:Whew!Ohboy.No I'm fine, really.I'llbe serious Deep breath OK, go on

HeadFirst:So whatdoesencapsulation protect you from?

ObjectEncapsulation puts a force-fieldaround myinstance variables,so nobody can setthem to, let's say, somethinginappropriaJ.e.

HeadFirstCan you giveme anexample?

Object:Doesn'ttake aPhD here.Most instance variable valuesarecoded with certainassumptionsaboutthe boundaries of the values.Like,thinkof all thethingsthat wouldbreakifnegative numbers were allowed Numberofbathroomsinan office.Velocity of

an airplane Birthdays.BarbellweightCellphone numbers Microwave ovenpowetHeadArst:Isee what you mean.Sohow does encapsulation let yousetboundaries?ObjectByforcingother code togothroughsetter methods That way, the setter method

canvalidatethe parameter and decideifit's do-able.Maybe the methodwillrejectitand

do nothing, or maybe it'llthrow an Exception (likeifit's a nullsocialsecurity numberfor a credit card application), or maybe the methodwillround the panlITleter sent intothe nearest acceptable value The point is,youcando whatever you wantinthe setter

method,whereas you can'tdoaT[!thingifyourinstancevariablesarepublic

HeadFirst:But sometimes Iseesetter methods that simplyset the value without ing anything:Ifyou havean instancevariable that doesn'thavea boundary, doesn't thatsener method create unnecessary overhead?A performance hit?

check-Object:The point to setters (and getters,too)is thatyou can c1umgeyour mind later,

without breaking any1Jo4y else's code! Imagineifhalf the people in your

com-panyused your class with public instance variables,and one day you suddenly realized,

"Oops- there's something I didn'tplan for withthat value, I'm goingtohave to switch to a

setter method." You break everyone'scode The cool thing about encapsulationis thatyou get to cJumgt )'CUT mind.And nobody gets hurt The performancegainfrom using variablesdirectly isso rniniscule and wouldrareIy ifDJn-beworthit

you are here ~ 81

Ngày đăng: 12/08/2014, 19:20

TỪ KHÓA LIÊN QUAN