P. 1
Lap Trinh Huong Doi Tuong Voi JAVA

Lap Trinh Huong Doi Tuong Voi JAVA

|Views: 1,086|Likes:
Published by tiep_ictu

More info:

Published by: tiep_ictu on Apr 09, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

04/11/2013

pdf

text

original

DoAN VAN BAN

_, ; J

LAP TRINH HUONG DOl lUONG

. . .

VOl JAVA

(Tai ban Ian thU nhat: co hi~u chinh va be sung)

"'" "" , .. - -

NHA XUAT BAN KHOA HOC VA KY THUAT

HA NQI- 2005

lei N61 DAU

Cac phuong ph ap huang doi t.uorig, d:).c biet la 19p trinli hUdng (toi: tli(Jng duoc xay dt;ing dua tren nhieu khai niern moi va duoc ho tro bdl nhieu c6ng cu, ngou ngir l(tp trlnh ([2], [8]) rat manh giup eho vice tao ra nhirng phan mcm ung durig e6 chat lucng cao, ngay cang dap ling tot hon yeu diu cua nguoi sl1 dung.

Ngon ngu J ava do gang Sun (htt.p:l/java.sun.com) phat tri&n tu (Uiu nhung narn 90 da trd thanh ng6n ng\:i 10P trinh huang doi tuong rat ducc ua chuong trong nhung narn gftn day nho mot srf dac di&m het sue thich hop vdi mang Internet, hi9n cHi va dang duoc dung ph6 bien treri toan the gidi nh&m dap ung cac yell du phil t tri6n cue ung dung tren marig phuc V\1 cho nhicu nguoi su dung voi nhling moi truong thuc hiQI1 pha n mern khac nhau, Java Ia m9t ngfm ngu lap trinh hoan chinh dUl.jC t.hiet kc theo each tiep can huang d6'i tudng va ke thua, su dung lai c6 narig crlp cua nhling ng6n ngli l<).p trinh trudc no.

vii mat cii phap, Java rfll gi6ng Val c++, mot ngon ngfi lap ti-in h hudng doi tuong dung ph6 bien nhat hi911 nay, nhung lOY-I di mot so tinh kha d\lllg (facilities) qua manh nhung kh6 va it dung, hoac thira ve mat ngon ngu [lJ nliu: 10Q.i b6 kc t.lnra nhieu ldp, vi chung co th6 to-o ra nhung luoc do dii liOu dang d(~ thi vii la nguyen nhan chinh co th5 gay ra st! phuc tQ.P va kh6ng darn bao tinh nhat qua n, tfnh dung dAn trong quan he thong tin (l10], [11]); Java khong' eho phep thao tac so h9C tren ki6u con tro vi day la ngu6n goe cua nhirng "can bo'' rilt kho phat hien rn khi bien dich, v .v ... M\1e dich chinh cua Java la: dan. ginn, than thien, huang etc/i tltrjng va each. tan nhiim tao ra nhiing ph6n mem. ting dung dQc l(1p vdi moi truimg 81t d~lI1g ([7], (8]).

Cuon sach nay gioi t.hicu ve lQ_p trinh huang doi tuong sv. dung ngon ngu 1(IP trinh Java. N9i dung chinh cua cuon sach dude trinh bay trong muoi chuong.

Chuong I trinh bay k hai quat each tiep can huang cliuc ntmg va l:)p trInh hlidng doi tucng, Ngon ngu mo hinh h6a h¢ thong UML [2] duoc 811 dung diS d(IC ta cue kh£li nie m co ban cua l(lP trinh huong dfli tucng. Chuong II gioi thieu chu trtnh phat triGn ella cue chuong trin h J ava, q ua trinh dich, thong dich vdi JVl\1 (Java Virtual Machine) va cac th~ loai chuong trinh ung dung, nhat lii ling dung uhung (applet) ella Java. Chuong III va chuong IV trrnh bay nhirng kluii nie m cd Sd nhflL cua mot ngon ngu l(tp trinh va neu each xay dung, t6' chuc ldp cac deli tti(ing trong C<1C chucng trinh ung dung. Cac 19nh clieu khien dong thuc hien chuong tiinh, dt)c biet 1;\ co ch(,{ xu 15' ngoai 19 ho trq d6 tao ra nhung chuong trinh hont dQng Uj't trong m91 tinh huang, thich ung duoc vdi moi dieu ki9Il tren co Sd ki6'm SOil t dude cac lui, cac ti nh

huang co th~ xay ra, duoc gidi thieu chi tiirt d chuong V. Chuorig VI de cap den lTIQt sblOp co sd nhfit cua Java va cac ki6u ca'u true du lieu ph6 dung nhu ki6u tuyen l(i.p (Collection), kiJu t(lp hop (Set), ki@u danh sach (List), v.v. Van de phat triJn nhirng ung dung applet va S\1 dung giao dien d6 hoa cua Windows (AWT) dudi dang cac tr ang Web vdi nhieu vi du minh hoa dude gidi thieu d chuong VII. Chuong VIII gi6i thieu cac lop xtt ly cac ludng du li(!u vao/ra chuan va nhung van de c6 l6 chuc, doc, ghi len cac loai t~p du lieu. Chucng IX trinh bay van d6 k@t nbi cac cd sd di1 lieu vdi JDBC nharn tao r a nhung h~ thong phdn mem tich hop t.u rihieu 10;::<i h9 thong thong tin khac nhau treri mang. Lfin tai ban nay dude b6 sung them chuong X gidi thieu cac thanh phan cua Swing, cho phep tao ra nhiing phan mcm rna ban "thay va cam nhan duoc''. Trong cac chuong co nhieu vi du 13. nhiing chucng trinh hoan chinh, minh hoa cho each S\1 dung nhung khai niern cia nell d tren,

Cuon sach duoc bien soan dua tren kinh ngb iern giang day giao trlnh phan tfch, t hiet ke'va l*p trinh hudng doi tUQng cua tac gin. trang nh ieu narn tai cac khoa cao hoc, dai hoc cua DR Qu6c Gia Ha N¢i, DR Bach Khaa Ha Noi, DR Khaa R9C Hue, v.v. CUeln sach co thJ dung lam giao trinh hoc t.:\p, Uti liOu tham khao cho sinh vien cac h(\ ky su, ctt nhan, hoc vien cao hoc CNTT va c{u; bn n quan tfim den vari de ll}p trinh huang dOl tuong d~ phat trl~n nhung ling dung dQc l*p vdi moi truong, hay dd xay dung cac Web Site tren ma ng.

Tac gia bay to long biet On chftn thanh toi cac ban d6ng nghiep trong Phong cac Hi; thong phan mern tich hQP, dQ.c biOt cam On TS. D(ing Thanh Phu, Vi~n Corig nghe Thong tin, TT KHTN & CNQG, P'fS.'l'S. Do Due Giao, Khoa Cong nghe, DH QG HN da dQng vien, gop y va giup da d~ hoan chinh n91 dung cuon sach nay. Xin cam en Nha xuat ban Khoa hoc va Kg thuat da ho tro va tao dieu ki(jn dJ cuon sach dude tal ban.

Mi).c du rat co g~ng nhung tai li~u nay chAc chin khorig trunh khoi rihung sui sot. Chung toi ra't mong nhan ducc cac y ben d6ng gop cua ban doc dd co chinh ly kip thdi.

Thu gop y xin gU:i vC: Nha xufft ban Khoa hQC va Ky thuat 70 Trfrn Hung Dao Ha N9i.

HfL N9i, tluing 5 nom 2005

Tac giii

CHuaNG I

GIOI THlt:U V~ LAp TRiNH

. .

Hl10NG £)61 Tl1cJNG

,. .,. _, - -- .....

1.1. CAC CACH TIEP C~N TRONG L~P TRINH

Phuong phap lap trinh truyen thbng chung ta van ap dung d6 la l¢p trinh. co diu true. Phuong phap l.$.p trinh nay thuc hien theo each tie'p can liuttrig chicc nang dua chu ye'u vao ciec ph/in. tach eric chiic nang chinh cua bai toan thanh nhirng chuc nang don gian hon va thuc hien lam min dan tu t.ren xu6ng (top-down). Thea each tiep can hvong chuc nang, chuong trinh dude xem nhu la mot t.$.p cac ham chuc nang, trong do du lieu va cac ham la tach roi nhau. Doi voi nhimg h~ thong ldn, phuc hQP, dQ ph uc tap cua chuong trinh tang len, su phu thuoc cua no vao cac ki~u du rna n6 xu ly cling tang theo. Cac kit5u du lieu duoc xli 1:9" trong nhieu chuc nang ben trong chuong trinh co cau true, va khi c6 su thay d6i ve ki6u du lieu thi cling phai thuc hien thay d6i d IDQi noi rna dii lieu do duoc sli dung, MQt nhuoc di~m nira cua 1~p trinh huang chuc nang Ia khi co nhieu nguoi tham gia xay dung chuong trinh, moi nguoi duoc giao viet mot s6 chuc nang (ham) rieng biet nhung Iai phai sli d ung chung dir lieu, Khi co nhu cau can thay d6i du lieu se anh huong rfit IOn de'n cong viec cua nhieu nguoi, v:v,

Phuong phap lap trinh rna ngay.nay chung ta nghe noi tdi n hieu d6 Ia l¢p trinh hianig doi tuong, Lap trinh hucng doi tudng dua tren ngn tang la cac dOL tuang. D6i tuong (thuc the) duoc xay dung tren co Sd gin du lieu vdi cac phep toan se th6 hien duoc dung each rna chung ta suy nghi, bao quat ve chung trong the' gidi thuc [3], [5]. Chang han, 0 to c6 banh xe, di chuyen dUQC va huang cua n6 thay d6i duoc bang each thay d6i tay 18.i, Tuong tu, cay l8. loai thuc vat c6 than go va 18.. Cay kh6ng phai la 6 to va nhirng gi thuc hien duoc vdi 0 to se kh6ng lam duoc vdi cay.

Lap trinh huang doi tuong cho phep cluing ta ket hop nhung tri thuc bao quat vii cac qua trinh thuc te voi nhung khai niern truu tuong duoc su dung trong may tinh. Chuong trinh hay h~ thong huang dbi tuorig duoc xem nhu la tap cac lop doi tuong tuong tac voi nhau dJ thuc hien cac yell diu cua bai toan d~t ra.

6

L9P trinh huang d6i tUI;:mg v6i Java

Nhu vay, hien nay chung ta c6 hai each tiep can co ban d~ phat trien cac h~ thong phan mern: lt6 la each tiep can huong chuc nang (Function-Oriented) va huong doi tuong (Object-Oriented). Ca hai each tiep can nay (Mu ap dung mot nguyen ly chung cl6 rna hinh hoa h¢ thong (d6 hi@u h~ thong) 18. thuc hi~n "ch.ia de'tr.i", phan ch ia bai toan thanh nhung don vi tlidng cloi don gian rna co th6 d~ dang quan ly duoc chung mot each c6 hieu qua.

D6 hi@u ro va ap dung hieu qua nhung phuong phap lap trinh ca n lua chon, chung ta d.n phan biet nhung cl$.C trung co ban nhat, danh gia nhung mat marih, mat yeu cua chung.

1.1.1. L";P TRiNH HUaNG CHUC NANG (THU Tl)C)

Nhung ngon ngii lap trinh hac cao truyen thong nhu COBOL, FORTRAN, PASCAL, C v.v ... , duoc goi chung la ngon ngu IQ-p trinh hiamg chiic nang. Thea each tiep can hudng chile nang thi mot h(! thong phan mem uU<;Ic xcm nhu IS. day cac cong vise (chuc nang) din thuc hien nhu nhap du lieu, tmh toan, xU' ly, lap baa cao va in fin ket qua v.v ... M6i cong viec d6 sc duoc thuc hien bdi mot so' ham nhat dinh. Nhu vay trong uim. cua erich ti€'p can. nay La eric ham chuc nang. Cau true cua chuong trinh duoc xay dung thea each ticp can huang chuc nang c6 dang nhu hinh 1.1.

Chuang trinn chinh W\.IN()

llinh j ,J, C(fu true ciia chuang trinh huang chuc nang.

L[).p trinh huong chuc nang (LTHCN) sl't dung ky tluuit ph/in. rii cric chicc nang (ham) thea erich tie'p c¢n top-down dJd' tao ra cj{u true pluin cap. Chuang trinh duoc xay dung thea each tiep can huang chirc nang thuc chat la ttip eric chuang trinh can (c6 th~ xem nhu la cac ham) rna thea do may tinh can thuc hien d4 hoan thanh nhung nhiem vu dat ra cua h¢ thong. '

Khi d~t trong tam vao cac ham thi dil lieu, nhung cai m a cac ham sU' dung d4 thuc hien cong viec cua minh lai i;rd tha nh thu yeu. Cai gi se xa y ra doi vdi dli 1i¢u va gin

Chuang t. Giai thi$u ve l{lp trinh huang doi tUQng

7

dfi lieu vdi cac ham nhu the nao? cung nhieu vftn de khac can phai giai quyet khi chung ta muon xay dung cac phuong phap phil hop d@ phat tri@n nhung h¢ thong phan mern giai quyet nhimg yeu cau d~t ra cua thuc teo Han nira, h~ thong luon 1a mot th~ thong nhat, do vay cac ham trong mQt cliuang trinh pluii c6 lien h¢, trao dd'i dUfJC voi nhau. Nhu chung ta da biet, cac ham (cac b9 phan chuc nang) chi c6 th~ trao d6i duoc vdi nhau th6ng qua cdc tham s6: nghia la pluii sU: dung bien chung (global). M6i ham c6 th~ c6 vung dil lieu rieng con goi la dft lieu CI;lC bQ (local). M6i quan h9 giua dii l ieu va ham trong chuang trinh huang chuc nang duoc mo til trong hinh 1.2.

Dilli$u chung Di1 li$u chung
(Global) (Global)
I I
I t
-v -l- ~ -lr
Ham_1 Ham_2 Ham_3
Di1 li$u ri€mg Di1 li$u rieng Di1 li$u rieng
(Local) (Local) (Local) Hinh 1.2. Quan h¢ giua du Ii¢1I va ham trong LTHCN.

Nhieu ham co th@ truy nhap, sU: dung dft lieu chung, lam thay do'i gui tri cua chung va vi v¢y nIt kh6 kie'm eoat. Nhat la doi voi cac chuong trinh ldn, phuc tap thi van de cang trd nen kho khan hen, Khi chiing ta muon thay d6i, b6 sung cau true dil lieu dung chung cho mot so' ham thi chung ta phai thay d6i hau nhu tftt ca cac ham lien quan den du lieu do. Nhat la d6i vdi nhirng chuong trinh, du an tin hoc ldn , phuc tap doi hoi nhieu nguoi, nhieu nh6m tham gia thi nhung thay deli cua nhung bien du lieu chung S8 anh. huang tai t{lt ca nhftng ai co lien quan tdi cluing,

M(lt u~c tinh mra cua each tiep can hudng chuc nang de nhan thay la tinh md (open) cua h¢ thong hem. Thu nhat, vi dua chinh vao chuc nang rna trong tluo: te'thl nhiem V(1 cua h¢ thong lai hay thay d6i nen kh i do muon cho h9 thong dap ung cac yeu cau thi phai thay d6i 19-i cau true cua h~ thong, nghia 13. phai thiet ke, lap t ririh 10-i h~ thong. Thu hai, viec sl'i dung cac bien dil lieu chung trong chuong trinh lam cho cac nh6rn chuc nang phu thuoc vao nhau ve cau true dil lieu nen cung han che tinh rnd cua h~ thong. Trang thuc te', co cau t6 chuc cua moi t6 chuc thuorig it thay d6i hon la chuc nang, nhiern vu phai thuc hien,

Mat khac, each tiep can huang chuc nang lai tach dii li¢u khdi clute nang xii If nen van de che giau, bao v~ thong tin trong h{! thong 1:) kern, nghia Ia van de an toan, an ninh. dilli¢u la rat phuc tap.

Ngoai ra each tiep can huang chirc nang cung kh6ng ho tro uiec sit dung lai va ke'

8

lQp trinh huang dOi tuc;sng vai Java

thua nen chat luong va gia thanh cua cac phan mem rilt kho duoc cai thien. Nhirng tro ngai rna chung ta da neu d tren se lam cho m6 hinh dU9C xay dung theo each tiep can huang chuc nang kh6ng mo ta duoc dfty uu, trung thuc h~ thong trong thuc teo

1.1.2. L~P TRiNH HVONG £)01 TVQNG

Nguoc lai, lap trinh hucng doi tuong (LTHDT) d(it trong tam uao cae doi tuong, yeu to' quan trong trong qua trinh phat tri~n chuong trinh va n6 khong cho phep du li~u tach biet, chuyen di)ng t1.j do trong h~ thong. Du lieu duoc g<'in chat voi cac ham thanh phan va chung duoc t6 chuc, quan ly truy nhap thea nhieu muc knac nhau.

LTHDT cho phep chung ta phan tich bai toan thanh ttip cdc thuc the" duoc goi Iii. cac lOp do'i tuang, sau do xay dung cac du lieu thanh phan cung vci cac ham thanh phan thao tac tren cac du lieu d6 va trao d6i vdi nhung dti tuong khac de; thuc hien nhung nhiern vu duoc giao.

Met chuong trinh, mot h~ thong duoc xem nhu: 18. mot tap cac lop dti tuong va cac dbi tuong do trao d6i vdi nhau thong qua viec g11i va nhan cac thong diep (message), do v$_y mot chuong trinh hudng doi tuong tnuc su co th~ hoan toan khong din stl dung bien chung [1], [3].

Lap trinh hudng doi tucng dua chu ye"u VaG cae doi tuang ; nen khi c6 nhu cau thay dbi thi chi can thay dbi d mot s610p co lien quan, hoac c6 th~ b6 sung m{lt SO lop mdi tren cd sd ke thira va slt dung lai nhieu nhat co th~. Ml'.it khac, nhu tren da phan tich, mot chuong trinh huang dti tuong c6 th~ khong si'1: dung hoac nan che' srt dung cac bien chung, do v$,.y d~ dang tao ra du'<;lc nhung h~ thong c6 tinh md cao hon.

Co ehe' baa bQe, ehe guiu. th6ng tin cua phuong pnap huang dti tuong giup tao ra duoc nhung h¢ thong an toan, an ninh. eao hon each tiep can huang chuc nang.

Hen nua, phuong phap hudng dti tuong con h6 tro rilt manh nguyen ly sit dung lai nhieu. riluit co the'va tao ra moi khd nang de' kt thua nhung lop da duoc thiet ke, lap trinh tot d~ nhanh ch6ng tao ra duoc nhirng phan mem co chit luong, gia thanh re hen va dap ling cac yeu cau ella nguoi S11 dung,

_ ,,_ ?,.",..._. , J

1.2. NHUNG KHAI NIEM CO BAN CUA LAP TRINH HUONG 001

. .

TUQNG

D~ ti~n loi va phu hop vdi xu the phat tri~n hien nay cua cong nghe thong tin, chung ta se sit dung UML (Unified Modelling Language [2], [7]) d~ di;lc ta nhtrng khai niem cd ban cua lap trinh huong dni tuong thong qua Rational Rose (http://www.rational.com) . UML la ngon. ngu rna hinh h6a hinh thiic, thong nhat va

Chuong t. Giai thi~u va l(lp trinh huang d6i tu(;mg

9

true quan. Ph§.n Ion cac thong tin trong mo htnh duoc the; hien boi cac ky hieu do hoa, bi@u do th@ hien moi quan h¢ giua cac thanh phan cua h$ thong mot each thong nhat va c6 logic chat che.

UML duoc S11 dung de; dtic td, xuy dl,lng va lam tai lieu cho cae tac phiz'm (Artifacts), cac kef qua cua cua cdc pha pluin tich, thifft hi oa l(ip trinh h.uang d6l tuong dudi dang cac bi@u do, ban mau hay cac trang Web.

UML la ngon ngU' chuan corig nghiep dE! lap k6 hoach chi bet phat tri§n phan mem. Hien nay nhicu hang san xu[(t phan mern Ion nhu: Microsoft, IBM, HP, Oracle, Digital Equipment Corp., Texas Instruments, Rational Software, v.v., 811 dung UML nhu la chuan cho ngon ngu mo hinh h6a h$ thong phan memo

Phuong phap huang doi tuong duoc xay dung dua tren mot tap cac khai niern co so:

1. D6i tuong (object),

2. Lop d6i tuong (class),

3. Triru tuong hoa du lieu (Data Abstraction),

4. Bao bQC va che giau thong tin (Encapsulation and Information Hiding).

5. Md rong, ke thua giU'a cac ldp (Inheritance),

6. Da xa va nap chong (Polymorphism and Overloading),

7. Lien ket dQng (Dynamic Binding),

8. 'I'ruyen thong diep (Message Passing).

1.2.1. £)01 TUQNG

D6i tuong la khai niern cd sd, quan trong nhat cua each tiep can huang dOl tuong. Doi tuong la thuc th6 cua h$ thong, cua CSDL va duoc xac dinh thong qua dinh danh ID (IDentifier) ella chung. Moi dOl tuang c6 tiip cdc dfic trung baa g6m d. cite phan tai san thuong Ia cdc dii lieu thanb. phan hay cac thuoc tinh rna ta cac tinh chat va cac phucng thitc, cac thao tac tren. cdc die lisu dE! xac dinh hanh vi cua d6i tuong d6.

D6i tuong la nhung thuc th§ duoc xac dinh trong thoi gian h$ thong huang dbi tuong hoat dQng. Nhir vay doi tuong c6 th@ bi~u dien cho nguoi, vat, hay mQt bang dU' lieu hoac bat ky mot hang thuc nao d6 d.n X11 15' trong chuong trinh. Dbi tuong cling c6 thE! 1a cac dir lieu duoc dinh nghia bdi ngudi S11 dung (nguoi lap trinh) nhu vector, danh sach, cac record v.v ... Nhiem vu cua LTHDT la phan tich bai toan thanh cac d6i tuorig va xac dinh duoc ban chat cua 81,1 trao d6i thong tin giua chung. Doi tuong trong chuong trinh dn phai duoc chon sao eho n6 th~ hien dude mot each gin nhat vQi nhimg thuc th~ c6 trong h$ thffng thuc,

NhU' vay, d6i tuong duoc dinh nghia mot each triru tuong nhu la mot khai niern, mot

10

lQp Irinh huang d6i tUQng vai Java

cau true g9P chung d. ph:in du lieu (thuoc tinh) vdi cac ham (phuong thuc) thao tac tren nhung du lii;u do va co thd trao d6i voi nhimg doi tuong khac. Thea qu an di8m cua nguoi lap trinh l31, do'; tuimg duqc xem. nhu' la uung h(J nhJ dliVc pluin. chia trong may tinh dil'Iuu trii dil lieu. va t(ip cae ham tac a(Jng tren di£ lieu g&n udi cluing, Bdi vi cac vung phan hoach bi? nho la dQc l~p vdi nhau nen cac cl6i tuong c6 th@ sU: dung bai nhieu chuong trinh khac nhau ma khong anh huong Hin nhau.

1.2.2. LOP DOl TUQNG

LJp la ban mau. hay mot kdu chung cho Utt ca nhung doi tuong co nhirng d¢c trung giong nhau; nghia la c6 cac thuoc tinh va hanh vi giong nhau. Doi tuong chinh 13. th~ hien (ca th@) cua mot lop xac dinh, Trang l~p trinh huong doi tuong, lOp duoc xern 13 dong nhat vdi ki6u du: lieu truu tuong (ADT - Abstract Data Type duoc Barbara di2 xuat vao nhung nam 70).

Phuong phap l~p trinh huang doi tuang la each ph an chia chudng trinh thanh cac den th~ (cac lop) bang each tao ra cac vung bi? nho cho ca du lieu Iftn ham va chiing se duoc slt dung nhu cac m au dd tao ra ban sao tirng doi tuorig khi chung duoc tao ra trong h¢ thong.

Nhiem vu cua nguoi lap trinh 13. tim each xac dinh dfty du, chinh xac danh sach cac lop dai dicn cho tat ca cac t.huc thd trong he thong va mci quan h¢ giua cac ldp doi tuong do l3], [5).

Nhu vay, lop chinh la tap cac doi tuong c6 cung cac thuoc tmh va hanh vi giong nhau. Cac tha nh phau cua ldp c6 th& chia thanh La vung quan ly chinh: c6ng khai (public), duoc baa v¢ (protected) va vung rieng (private). Trang ngon ngu mo hinh h6a thong nhat UML, cau true cua ldp thuong dude dac ta bdi: ten cua lop, tap cac thuoc tinh va t~p cac ham.

Hinl: 13. LOp Student trong UM!..

Lop c6 ten la Student. Lop c6 ba thuoc tinh: StudentNo co ki6u Integer la sd huu rieng (private), bi kh6a; thuoc tinh FName c6 kidu String la cong khai (public) va thuoc tinh LName la dUQC bao v~ (protected). Lop Student co ba ham : getStudentNo(), getFName(), getLName() deu 13. cong khai,

Chuang I, Giai thi~u ve I¢p trinh huang doi tuc;mg

11

1.2.3. TRUU TU<;jNG HOA OU LI$U

Truu tucng hoa la each bi6u dien nhung dac tinh chinh va 1>0 qua nhung chi tiet, Triac tuang hoa la s1,1' rnd rong khai niern ki6u du lieu va cbo phep djnh nghia nhiing phep toan truu tuong tren cac da lieu truu tuong.

D~ xay dung cac lop, chung ta phai S11 dung khai niern triru tuorig h6a. Vi du, chung ta c6 the; dinh nghla mot lop la danb sach cac thuQc tinh truu tuong nhu la k ich thuoc, hinh dang, mau va cac ham xac dinh tren cac thuoc tinh nay d~ m6 ts. cac doi tuong trong khong gian hinh hoc, Trang lap trinh, lop duoc S11 dung nhu kiflu dit lieu truu tuang.

Khi xay dung phan mcm thi nguyen ly truu tucng b6a dude th uc h ien thong qua viec triru tuong b6a cac 'chuc nang, bam (thuat twin) va truu tuong h6a cac ki6'u da li$u nguyen thuy.

1.2.4. BAD BQC vA CHE GIAU THONG TIN

Viec d6ng goi dii lieu. va cdc ham vaa m(jt dan. vi cdu true (goi la lop) duoc xem nhu mot nguyen t~c baa boc thong tin. Ky thuat nay cho phep xac dinh cac vung d;;ic trung rieng, eong khai hay a1.Lrje baa v¢ bao g6m ca du li$u va cac diu l$nh nham ddu khie"n ho(ie han ehe' nhiing truy nluip tiLy tien. cua nhimg doi tuong khac, Du lieu duoc t6' chuc sao cho the gidi ben ngoai (cac doi tudng d lop khac) khong truy nhap dude vao nhung thuoc tinh rieng va chi cho phep cac ham trong cung kip hoi),c trong nhung lop c6 quan h$ ke thua voi nhau duoc quyen truy nhap den vung duoc bao v$. Vung cong khai cua lop thi cho phep moi d6i tuong duoc phep truy n hap.

Chfnh cac ham thanli pluin. cong khai eua lop se dong vai tro nhu la giao dien. giiia cdc doi tuang va vdi pnan con lai cua h~ thong. Nguyen d.c bao boc du lieu d6 ngan earn su truy nhap true tiep trong l<).p trinh dude goi Ia su ehe gitiu thong tin.

Nguyen ly bao b9C che giau thong tin cua lop d6i tuong duoc rna t,\ nhu trong hinh l.1.

;-- Vung private

;-- rl DCt li$u rieng I .......
J
H Ham rieng t.......
'-- J' I r-
;- Vung public \

-..J k
""'-l DCf li$u cong khai I'"
- ~ Ham cong khai I ......
I ....... Hinh 1.4. Baa b9C va che gidu thong tin ~iia lup dOl tuang,

12

L¢p trinh huang doi tUQng vOi Java

?.... -".... - .#' ,

1.2.5. su Md RQNG, KE THUA GIUA CAG Lap

Nguyen 15' ke thua cho phep cac doi tuong cua lOp nay duoc quyen s-li dung mot so tinn chat (ca dil lieu va cac ham thanh phan) cua cac lop khac, M9t ldp c6 th& la Zap con (lap dan xuat) cua mot lop khac, nghia la c6 thE! b6 sung them mot su ttnh chat dE! thu hep pharn vi xac dinh cac doi tuorig trong lOp mdi cho phu hop vdi ngu carih trong th uc te.

Theo nguyen 15' chung cua ke thira thi chi nhiing thuoc tinh, ham thanli pluin. duqc bao v~ va cong khai la duac quytn he'thiLa, con nhung thuoc tinh, ham thanh. phan. rieng la hh6ng duo: phep he'thila. Nhung thuoc tinh va ham duoc ke thira tu lap cha (lap ca Sd) duoc xcm nhu la "tai san" cua chmh cac doi tuong con chau, chung c6 quyen Slt. dung rna kh6ng can phai khai bao hay dinh nghia lai. Nhu vay, nguyen 15' ke thira trong l~p trlnh hucng doi tuong hoan toan dong nhat voi nguyen 15' ke thua gia san trong xii hQi loai nguoi.

Phuong phap hudng doi tuong n6i chung h6 trQ hai nguyen 15' ke thira: he'thila den ua he" thila b(;i. Ke thira don la mot lop c6 thE! ket.hua tu mot lop cd Sd, con ke thira bQi la mot ldp c6 the; ke thira til nhieu hon mot ldp co sd. Ngon ngu C++ h6 tro cii hai nguyen 15' ke thua, nhung Java chi h6 tro thuc hien he'thila dan [81.

Nguyen 15' ke thira don ho tro cho vise tao ra cau true cay phan cap cac lop. Vi du, mot truong dai h9C dao tao sinh vien c6 ba khoa: Khoa Xa h9i, Khoa Cong ngho Thong tin va Khoa Toan. Chung ta c6 thE! xay dung lop Sinh uien la lop cd sd dEl tii d6 xay dung tiep ba ldp ke thua la: Khoa Xii h(;i, Khoa Toari va Khoa CNTT. H~ thong se duoc thiet ke thanh cac lop ke tnua va dl1QC mo tii trong UML nhu sau:

H inh J.5. C au true phlin ca"p cac lOp thea quan he ke" thua trong U M L.

Trong LTHDT, khai niem ke thua keo theo y WOng sv. dung lai, Nghia la tir mot lop da dude xay dung chung ta c6 th@ b6 sung them m9t so tinh chat tQ-O ra mot ldp mdi ke thua lop cu rna khong lam thay d6i nhirng cai da co.

Khai niern ke thira duoc hi@u nhu cd che' sao chep 8.0 khong den dieu. Trong thuc te, moi viec xay ra tua nhu nhung ldp co sd deu duoc sao VaG trong ldp can (lop d~n xuat) mac du dieu nay khong duoc cai dat tuorig minh (nen g9i la sao chep ao) va vi@c sao chep chi thuc hien doi vdi nhiing thong tin chua duoc xac dinh trong cac ldp

Chuang t. Giai Ihii?u ve IQp trinh huang doi tUc;lng

13

co sd (sao chep khong don dieu), Do vay, c6 th~ di@n dat co che' ke" thua nh u sau:

1. Lop A ke" thua ldp B se c6 (kh6ng tuong mirih) tilt d. cac t.huoc tmh, ham da duoc xac dinh trong B. d nhirng vung duoc phep ke" thua (dude baa v~, cong khai),

2. B6 sung them mot so thuoc tmh, ham d~ rna ta duoc dung cac hanh vi cua nhimg d6i tuong rna lop A quan 1Y.

1.2.6. £>A x~ (lUONG UNG BOI) VA N~P CHONG

M9t khai niem quan trong nira trong LTHDT la khai niern da XI.l tuong tu nhu trong toan hoc. Da xa la ky thuat duoc S11 dung d~ rna ta khd nang gl:tl mot thong di~p chung tai nhie'u dOL tuang ma m6i dOL tuang lai co each xl:t ly rieng thea ngft cdnh. eua minh,

Da X:;J. d6ng mot vai tro quan trong trong viec tao ra cac do'i tucng co cau true vdi nhung n9i dung thuc hien khac nhau rna lai e6 kha nang S11 dung chung mot giao di¢n (cung rn¢t ten goi). Theo mot nghia nao d6, da xa la su rno rong khai niem S11 dung lai trong nguyen 1y ke" thua, Hinh 1.6 cho chung ta tha'y ham c6 ten la VeO c6 th6 si't dung df ve cac hinh khac nhau phu thuoc vao doi tuong hi cac hinh khi goi d~ thuc hien.

Tam giac, Hinh trim va Hinh. ehi1 nh¢t lil cac ldp can cua ldp Hinh, Ham VeO 13. ham da xa va n6 duoc xac djnh tuy thea ngu canh khi s1.1 dung. Khi goi thuc hien d6i tuong la Tam gitic thi se ve tam giac, neu doi tuong Iii hinh iron. thi ve hinh tron, V.v.

Hirth J .6. Tuang ling b¢i ella ham YeO.

Nap chong (Overloading) la mQt truong hop cua da xa. Nap chong Ia kha nang cua mot khai niem (nhu cac phep toan chang han) c6 the; dude s\1 dung vdi nhieu nQi dung thuc hien khac nhau tuy theo ngir canh, cu thf la tuy thuoc vao kieu va so cac tham so' ella chung, Vi du, ham CongO co th~ duoc nap chong d@ cong cac so nguyen (int), so thuc (float), so phuc (Complex) hoac ghep cac xau ky tv (String), v.v.

int Cong(int, int):

II Cong hai s6' nguyen

14

LQp trinh huang doi tuc;mg vai Java

float Congtfloat, float);

Complex CongrComplcx, Complex); String Cong(String, String);

String Cong(String, in t);

" Cong hai so thuc II Cong hai so pnuc II Ghep hai xau

II Ghep mot xau vdi mot so nguyen

1.2.7. LIEN KET DONG

Lien kct thong thudng (liDn ket tinh) 1ft dang lien kct ChIQC xac dinh ngay khi dich chuong t ri nh, Hau het cac chucng trinh dtIQC viet hang Pascal, C deu lA dang lien ket tinh. Lien kef d¢Jng la dang lien kCt cac ham, chuc nang khi chudrig trinh thuc hien cac ldi goi cac ham, chuc nang do. Nhu vay trong lien kct dong, nQi dung: cua doan chuong trinh ung vdi chuc nang, ham se khong duoc xac dinh eho den khi thuc hien lei goi tci chuc nang, ham d6. Lien ket dQng lien quan chat chB vdi nhtrng khai niem eta xa va ke thua trong lap trinh huang doi tuong. Chinh nho khai niern lien ket dong rna nhieu khai niem cua lap trinh huang d6i tuong nhu khai niern da xa thuc hien duoc.

Chung ta hay xet ham Ye() trong hinh 1.6. Theo nguyen 1y ke thua thi moi deli tuong deu ell th6 sli dung ham nay dt; ve cac hinh C\1 th6 khi h9 thong thuc hien. Ham YeO cillQC di nh ngh1a 10-i a trong cac lop dflll xuat d~ ve tam giac, hinh tron hay hinh chir nhat thea cac thuat toa n tuong ung. Khi thuc hien, vi du: ncu d6i tuong Hinli la Hinh. trim. thi h~ thong se lien kct voi ham \leO dlIQC dinh nghia trong lop Hinh. trim de: ve hinh tron,

1.2.8. TRUYEN THONG f)1~P

Chuong trinh hudng doi tuong (dude thiet ke va l$,p trinh thea phuong phap huong d6i tuong) baa gam mot tap cac doi tuong va moi qu a n h~ giira cac cl6i tuong d6 vdi nhau. Vi vay, l*p trmh trong ngon ngii hudng d6i tuong bao gam Cal' buoc sau:

1. Tao ra cac lop doi tuong va mo ta hanh vi cua chung;

2. Tao ra cac dOl tuong then dinh nghia cua cac lop;

3. Xac dinh su trao d6i th6ng tin giua cac d6'i tuong trang h$ thong,

Cac d6i tuong giri va nhan thong tin trong h~ thong nuong d6i tuong cung gi6ng nhu can nguoi trao d6i vdi nhau trang xa hoi, Chinh nguyen ly trao d6i thong tin bang each truyen thong diep eha pnep chung ta de dang xay dung duoc h~ thong mo phong gfin hen vdi thuc te. Truyen thong diep cho mot d6i tucng tuc la bao cho no phai thuc hien mot viec, mot yeu cllu (thinh cau) nao do. Cach ling xu ella d6i tudng se dU:QC rna tit a trong lop thong qua cac ham cong khai (hay con duoc goi la lop dich vu).

Chuang I. Gi6i thi~u ve IQp trinh hu6ng d6i tUQng

15

Trang chuong trinh, thong di~p gui d§n cho mQt doi tu't;!ng chinh la et~ yeu cau thuc hien mot c6ng viec cu th~, nghla la su dung nhung ham tuong ling d~ xu 15' du lieu eta duoc khai bao trong lop doi tucng d6. Vi vay, trong thong di~p phai chi ra ducc ham can thuc hien cua doi tuong nhan thong diep. Hdn the nira, thong diep truyen di phai xac di nh ten doi tucrig, ten ham (thong diep) va thong tin truyen di, Vi d1,1, khi h¢ thong may tinh muon in lTI9t t~p dataFile thi may tfnh hien thci (:Computer) gfri cte'n cho doi tirong :PrinterServer mot yeu d.u Print( dataFile). BQ p han dich V1.,l may in se kj~lTI tra xem n§u may in dang ban thi luu ysu diu d6 vao hang doi b&ng each gui cho (:Queue) thong diep 18. Store (dataFi le), nguoc lai gi'ti yeu cau in Print(dataFile) cho doi tucng Printer. Heat clQng trao d6i thong di~p giua cac etoi tuong tren c6 th~ mo ta trong UML nhu hinh 1.7.

H ill II } _7_ Truyen thong di¢p giiia cac dlfi tuong.

Moi doi tuong chi t6n tai trong thoi gian nhat dinh. Doi tuong duoc tao ra khi n6 duoc khai bao va se bi huy bo khi chuong trtnh ra khoi mien xac djnh ella doi tucng d6. 81,1 trao d6i thong tin chi c6 th~ thuc hien trong thci gian t6n tai cua doi tuong.

.. _'??........ , ",'

1.2 .. 9. GAG UU DIEM GUA LAP TRINH HUdNG £)01 TUONG

. . .

Nhu tren eta phan tich, lap trinh huang doi tucng dern lai mot 801c;li the cho ca nguoi thiet ke lftn nguci lap trinh. Cach tiep can huang doi tuong giai quyet duoc nhieu van ete ton tai trong qua trinh phat tri~n phan mem va tao ra ducc nhirng san pham ph§.n mern c6 chit lucng cao. Nhung phuong phap nay md ra mot tri~n vong to Ion cho nhirng ngudi l$.p trinh. Hy vong se c6 nhieu san pham phan rnem tot han, dap ling ducc nhimg tfnh chat, v~ san pham chat lucng cao trong C6ng nghe phan mern va nhat la bao tri h~ thong it ton kern hen. Nhung uu di~rn chinh cua LTHDT la:

1. Thong qua nguyen 15' ke thua, chung ta c6 th~ loai bo ducc nhimg doan chuong trinh lap lai, du thua trong qua trinh mo ta cac ldp va md rong kha nang si't dung cac ldp dii dude xay dung.

2. Chuong trinh duoc xay dung tit nhung don th@ (doi tuong) trao d6i voi nhau nen viec thiet ke va lap trinh se duoc thuc hien thea quy trinh nhat dinh ehli khong phai dua vao kinh nghiern va kg thuat nhu trudc. Dieu

16

l¢,p trinh huang d6i tuc;mg v6i Java

nay dam bao rut ngan duoc theli gian xay dung h¢ th6ng va tang nang suat lao dong.

:3. Nguyen ly che giau thong tin gnip nguoi l$.p trinh tao ra duoc nhimg chuong trinh an toan khong bi thay d6i boi nh.ung doan chuong trinh khac mot each tuy tien.

4. C6 th~ xay dung duoc anh xa cac doi tuong cua bai tOElTI van dOl tuong cua chuong trinh.

5. Cach tiep can thiet ke c1;;it trong tam van dli lieu, giup chung ta xay dung duoc rna hinh chi tiet va phu hop voi thuc teo

6. Nhirng h~ thong huong doi tuong de md rong, nang cap thanh nhirng h9 IOn hon.

7. Ky thuat. truyen thong di~p trong viec trao d6i thong tin giua cac doi tuong giup cho viec rna ta giao dien vci cac h~ thong ben ngoai trd nen don gian hon.

8. C6 thf qu an ly duoc di) phuc tap cua nhung san pharn phan memo

9. Khong phai trong h~ thong hudng dOl tuong nao cung co tit ca cac tinh chit neu t ren. Kha nang xay dung duoc chuong trinh c6 cac tinh chat d6

• con phu thuoc van linh vue ling dung cua du an tin hoc va vao phuong phap thuc hien cua nguoi pnat trifn pnan memo

., ,... .....A.... ,. ~

1.3. CAC NGON NGU" L~P TRINH HUONG DOl TUQNG

Lap trinh huong doi tuong khong la dac quyen cua mot ngon ngli nao d$-c biet. Cling gi6ng nhu ll}p trinh c6 cau true, nhung khai niem trong l$.p trinh huang doi tuong c6 th@ cai d0-t trong nhung ngon ngu l$.p trinh nhu C hoac Pascal. Tuy nhien, d6'i vdi nhung chuong trinh Ion, phuc hop thi van de l$.p trinh se trC! ne n phuc tap, neu sU' dung nhung ng6n ngu khong phai la ngon ngu huang d6i tuong thi phai thuc hien nhieu thoa hiep, Nhung ngon ngit duoc thiet ke dac biet, ho tro cho viec mo ta, cai d0-t cac khai niern cua phuong phap huang doi tuong duoc goi chung la ng6n ngu huang d6i tuong.

Dua vito kha nang dap ling cac khai niern ve huang d61 tuong, chiing ta c6 thf chia ra lam hai loai:

1. N g6n ngu lap trinh dua tren doi tuong (object-based),

2. Ng6n ngu lap trinh huang doi tuong (object-oriented).

Lp,p trinh dua tren. dOL tliqng 18. ki@u ll}p trinh h6 trQ chinh cho viec bao b9C, che giau thong tin va dinn danh cac doi tuong. Ll}p trinh dua tren dOl tuong co nhiing d$.c tinh sau:

• Bao b9C dli li¢u,

• Co che' che giAU va han che truy nhap dft lieu,

Chuang /. Gioi thilf!u ve Iqp trinh huang doi tUQng

17

• Tu dQng t9.0 lap va h uy bo cac d6i tuong,

• Ttnh da X9..

Ng6n ngu h8 tro cho kieu lap trinh trcn duoc goi la ng6n ngu lap trinh dV8. trcn doi tuong. Ng6n ngu trong lop nay kh6ng h8 trey cho viec thuc hien ke thua va lien ket dong. Ada IiI ng6n ngu l$p trinh dua tren d6i tuong.

Lap trinh huang d6i tucng 1;\ k ieu lap trinh dua tren d6i tuong va b6 sung them nhieu cau true d~ cai dat nhfrng quan h~ ve ke thua va lien ket dong. Vi vay d;).c tinh cua LTHDT co thJ viet m(Jt each ngan gqn nhu sau:

Cac d¢c tinh. dua tren dol. tlilJng + he'thita + lien kef d(jng.

Ng6n ngu h8 tro cho nhung d~c tinh tren durrc goi la ngon ngtr LTHDT, vi du nhu Java, C++, Small talk, Object Pascal hay Eiffel, v.v ...

Viec chon mot ngon ngir d@ cai dat phan mom phu thuoc nhieu van cac d<).c tinh va yeu cau cua bai toan ung dung, van kha nang SD: dung 19.i cua nhirng chuang trinh dB. co va van tS chuc ella nh6m tham gia xay dung phan memo MQt trong nhung ngon ngu lap trinh huang d6i tudng thuc s\i duoc 8D: dung ph6 bien hien nay la .J ava [8] 8e duoc gi{ji thiou chi tiet d cac chuong sau.

BAI T~P

1.1. Neu cac dac trung cd ban cua each tiep can lap trinh huang chuc nang va li),p trinh huang d6i tuong.

1.2. T9.i sao lai goi khai niern lop la ki~u du lieu truu tuong trong lap trinh huang d6i tucng.

1.3. Nell nguyen 1:5' hoat oQng cua khai niern da xa, tucng ung b9i trong lap trinh hucng doi tuong, khai niern nay thuc hien duoc trong li;tp trinh huang chuc nang hay kh6ng, tai sao?

1.4. Khai niem ke' thua va 8D: dung 19.i trong lap trinh huang d6i tuong la gi?, ngon ngir li),p trinh C++ va Java ho tro quan h9 kc thua nhu the nao?

2LTH-A

CHUCJNG /I

GI0I ~U vt L~P TRINH V0I JAVA

2.1. GIOI THleU CHUNG

Cac chuong trinh dich cua cac ngon ngir l(lp trmh truyen thong nhu C / C++, Pascal thuong dich cac tep chuong trinh nguon sang cac diu lerih d(ic biet rna may t.inh cua ban hi~u duoc, Nhirng ngon ngu nhu C/C++ duoc xay dung treri co sCi tao ra nhung chuong trinh dich t6i uu voi rna may thuc hien hieu qua, nhanh va li nh hoat. Chu trinh phat tri@n va thuc hien cua chuong trinh viet bang nhirng ngon ngu truyen thong nhu C/C++ c6 th@ duoc mo ta nhu sau

~ -- ~ ~ -- - - - - ~ - ~ ~ - ~ ----- -~ ~

.--------~-__, "~ Chuang

, trinh ngu6n

,

,

,

T$p cai (Header File)

T $p thu vien (Object File)

, , ,

,

,

,

Tep chua chuang trinh chfnh

main()

{ }

Tep rna dich (Object File)

Tep chuang trinh thuc hien

(Executable File)

Dich

ce loi (Debug)

Chuang trinh ung dl.:Jng hien thai

Kiern tra (Test)

Hinh 2.1. Chu trinh pMt (riin va thuc hien ctia chuang trinh CIC++.

Tuy nhien d@ t6i uu h6a duoc chuong trinh dich thi n6 phai duoc thuc hien dua tren mot kiln true (ttip cac lenh) xa(' dinh, nghia 103. phu thuoe VaG cau hinh cua may dfch. D~ tao ra duoc su doc l(lp tuong d6i thi chuang trinh cua ban phai dich lai dJ phu

20

lQp trinh huang doi tuc:mg vai Java

hop vdi kien true may moi moi khi ban thay 06i moi truorig thuc hien chuang tri nh.

Hien nay c6 nhieu loai may tmh vdi nhieu cau hinh k hac nhau, Thong thuong voi moi loai ung dung cluing ta chon mot loai may tinh.va cau hinh hop ly dd phat tri@n chuang trinh cho hieu qua. Tuy nh ien, khi dieu kien thuc hien chuang trinh thay u6i thuong gay rat nhieu trd ngai cho nguoi s\t dung. Do d6 nhung nguoi phat tridn chuang trinh ung dung (nguoi lap trinh) muon phat kien nhirng phuong thuc lam viec mdi c6 th@ doc lap duoc vdi nhjrng thay d6i cua rnoi truorig va mong muon co s1,1' h6 tro cua cac ngon ngii Iap trinh.

Dac biet, truing Internet duoc xcm nhu la mang cua nhieu ma ng khac nhau ve nhieu Iinh vue, ca. phan cung Iftn p h an memo Mang cung cap nhieu dich vu tien lei cho nhieu ung dung khac nhau, nhat la cac ung dung tren mang cua cong ngh¢ Web. D@ dua duoc cac yeu to lap trinh len mang va ke't hop vdi Web thi kh6ng nen S11 dung cac chuang trinh viet bang C/C++, bai vi:

1. Van de an tcan, an ninh dti li$u tren mang khorig dam baa,

2. Quan trong han la cac chuang trinh C/C++ duoc dich sang mot rna may co cau hinh co dinh, vi vay khi duoc nap tU tren mang xuong mot may co cau hinh khac se khong thuc hien dude, Vi du, mfrt chuang trinh da. duoc dich d Machintosh thi se khong thuc hisn duoc d Windows va nguoc lai.

Dieu rna chung ta muon nhat hien nay lil can co mot ngon ngu thong dich. that ma nh dg; khac phuc nhung nhuoc di6m tren, d~c biet d@ phat trien duoc cl~ dang cac ung dung vdi Web tren rriang. Nhung thea nguyen ly cua chuang trinh thong dich (Interpreter) thi no thuc hien kha cham. Neu chuang trinh thong dich phai thuc hien phan tieh chuang trinh ngudn m6i khi thuc hien thi cac chirong trinh ung dung se rat cham.

Java vuot qua duoc cac nhudc di6m tren bang each dich cac chuang trinh ngu6n sang ngon ngu may [10 khong phu thuoc vao chip (h~ lenh. ClJ the) nao ca va sau do khi can thuc hien se thong dich sang h~ may C1,l thK Ket qua cua chuang trinh dich khong phai la rna dich (Object Code) nhu ket qua ella cac chuang trinh dich truyen thong rna la chuoi cac bytes co Sd baa gom cac rna l$nh thuc hien (Opcode) va cac tham so cua may ly thuyet (may ao). May nay duoc goi 18. may Java :10 (JVM . Java Virtual Machine). JVM co th@ nhung vao ba't ky mot bi@u dien, mot moi truong C1,l th@ rna ban co. Khi cai d~t tren mot moi trvC1ng xac dinh (may co cdu hinh co'dinh) thi phan mem du<;lc thong dich va JVM trd thanh may C1,l th@ d@ co thi thuc thi ung dung cua ban. Chuang trinh Java dude thuc hien nhu sau:

Chuang II. Gioi thi~u ve IQp trinh voi JAVA

21

Chuang trinh Cac ma byte
ngu6n ... (Byte Codes)
(Source Codes) ..
Dich •
(Compiler) Cac ma byte
Tep chuang trinh java (Byte Codes) .jev«

Tep cac lop .class

Kiem tra cac byte codes

B6 nap lop (class loader)

May Java ao
(Java Virtual Machine)
+ Th
Phan cung va h~ dieu hanh
(Hardware and OS) ons dich (I nterpreter)

Ma thuc hi$n .exe

l linh 2.2. Qua trinh dich wi" thong dich chuang trinh Lava.

Cong nghe .Iava giai qllyct vari de toe dQ bAng each dich chuong trinh nguon sang cac mii byte (byte codes). Khi JV1-1 thuc hien, n6 se tim cac doi tuong d.n tham chicu cua cac lop trong eh uong trrnh chinh (chlidng trinh ling dung) 6 thoi di6m thuc hien d~ nap chung xu6ng. Qua trinh phat tri@n va thuc hien chuong t.rinh -Iava thuc hien nhu sau:

Byte Codes

Lop (Jng dl,lng MyClass{}

Dich

Ki~n tra va thong dich

Chironq trlnh (Jng dl,lng hien hanh

Hinh 2.3. Qua trinh phdt tn·tn chuang trinh Java.

Thu vien Byte Codes

Nap cac lop tham chieu

Nhu vay, Java la ngon. ngu d¢ng kh6ng yeu d.lI moi thu phai s~n sang (xac dinh) d hie dich rna JVM: e6 th@ nap cac lop (cae dOL tlirjng) can thie] (t~p .class) d@ lam viec khi thuc hien chuong trinh ling dung, Thong thuong, m6i lop trong chuong trinh se duoc djch sang mot t~p co duoi (phan md rong) la .class. Thea each tS chuc cua Java

22

LQp trinh hubng doi tU<;lng vbi Java.

kh6ng co su phu thuoc giua cac t¢p nguon trong qua trinh dich, Nghia 18. khi cac giao dicn (m6i quan h¢ giita eric lap) chua hi thay d6i thi kh6ng can phai dich lai cac t~p chua rna ngudn cua rihung lop duoc tham chien hoac cac ldp tien Ich, tru' khi chinh cac ldp nay hi thay d6i. Chung ta chi phai dich lai nhimg tep .java mdi hoac nrurng t~p da bj thay df)'i.

T6m 1<:1-i, C/C++ va Java la nnung ng6n ngii nham nhung muc dich khac nhau.

y Doi vdi C/C++ cai chinh la toc dq, manh me va uyen chuyen trong l~p trinh. Khi thuc hien chuong trmh C/C++ thi moi viec cua h~ thong deu phai bat dau va ket tnuc a mot chuong trinh con dac biet, ham maini). Chung ta c6 th@ sli dung thu vien dong, nhiing t.hu yeu diu duoc lien kgt lai khi can, nhung ve t6ng th@ Ia phai dinh nghia va xac dinh ngay tU truc!c khi dich.

y D6i voi Java m uc dfch chinh la: don gian, than thien, huang doi tuong va each tan nham tao ta nhung phan mem dQc lQ.p vci m6i truong, Khi chay mot chuong trinh ling dung Java thi cAn chi' ra nhung ldp doi tuong rna ban muon chung thuc thi nhung cong viec can thuc hien va JVM se nap cac lop do xuong khi c6 nhu cftu. Val co che thong dich thi phan IOn cac yeu cAu chi tiet se duoc xac dinh a thoi di@m thuc hien, chu khong phai thoi di~m khi dich, Do vay b<) nhd dUQC cap phat dong Iuc thuc thi chuong trinh.

2.2. MOl TRUONG JAVA

Nhu tren chung ta da khang dinh, chuong trinh Java c6 th~ dich va thuc hien trong moi rnoi truong dieu hann, mien la d do c6 chuong trinh thong dich (may Java do - JVM). Van de di;it ra 113. lam the nao d~ kct h9P dU9C co che thong dich Java vdi cac bQ trinh duyet Web (Web Browsers). Nhimg van de lien quan la:

» Co che xli ly cac Web Site,

y Tai sao lai sli dung Java cho c6ng nghe Web,

y T6 chuc thuc hien cac du an ling dung vdi Jaua.

o Xli ly cac Web Site

MQt di)c trung cua Java duoc dac bi~t chu y la kha nang nap xufmg (downloaded) Web thea yeu d.u va thuc hien chuong trinh ling dung tren cac may khach. Truce khi Java xuat hien thi Web dl1QC xem nhu la nguon cung dip cac tu lieu (document) va chi thuan tuy la cac tu li%u.

Web se duoc tang them gia trj khi co them cac dang chua them thong tin b6 sung. Trude day cac tu lieu chi chua cac du li~u tho, vdi Jaua Web duoc b6 sung them su lien ket giira cac mtiu du lieu lien quan d§ bien d6i nhirng du lieu tho thanh nhtrng

Chuang /I, Giai thl$u ve 19P trinh vai JAVA

23

thong tin.

Ban than Java la bien deli thong tin. Thay vi hi~n thi so db dli lieu, cac b(> trinh duyet duoc Java h6 tr<;l cho phep thao tac tren cac du lieu, thong tin, thuc hien phan tich, thay d6i kich thuoc, pham vi xV ly cac dii' lieu d~ c6 nhung thong tin sinh dQng.

Q Java v a Web

D~ tra loi duoc cau hoi tai sao dn Java cho Web, chung ta phai narn hit duoc cac dac di~m cua Web.

(i) Dqc l¢p u(ji moi truimg (Platform Independent)

+ 'I'ruoc tien cac chucng trinh chay tren Web doi hoi phai kh6ng phu thuoc vao rn6i truong. Web phai mo dOl voi moi nguoi thong qua cac giao thuc (protocol) chuan d~ thuc hien tren moi rn6i truong.

+ Ngon ngir thong dich r!lt phil. hop voi muc dich cua Web: Trinh duyet thong dich cac lenh cua HTML sang cac tu lieu c6 khu6n dang dep sinh d9ng, dap trng thea moi yeu cau,

+ Khi thuc hien chuong trinh, JVM narn giira phan cling va chuang trinh ling dung, lam nhiern vu thong dich cac ket qua d dang rna byte vao rn6i trudng cua may khach d~ thuc hien, do vay dam baa duoc tinh d9c lap,

(ii) Dam baa an ninh. (secure) thong tin

+ B9 dich Java dam baa kh6ng nap cac chuong trinh virus vao chuang trinh ling dung, Khi chuong trinh Java duoc nap xuong thea yeu du cua Web, n6 kiern soat tilt ca cac rna byte cua chuang trinh duoc nap xuong va dam - baa rang chung phai twin thea cac qui dinh, cac rang buoc cua ng6n ngii'.

+ Mi;i.t khac, ldi goi cac phuong thuc trong rna byte kh6ng phai la cac dja chi nhu trong cac ngon ngir truyen thong rna la cae ten goi (thong qua dtnh danh doi tuang). Trang cac chuong trinh C/C++, cac loi goi ham 18 cac dia chi va rat kh6 kiem scat vi trong d6 cho phep cac phep nhay tu do toi bat ky dia chi nao d6 khi thuc hien chuong trinh. Trang Java, cac d6i tuong va cac phuong thuc rna ta cac hanh vi cua cac d6i tucng dt£u duoc X8.C dinh bang dinh danh do vay d~ dang ki~rn soat chung va dam baa an ninh cao.

(iii) Dam bao an toan (safe)

+ Nhieu khi se rilt la nguy hi~m neu xay ra cac sl,i co tran he) nhd, vuot qua cac chi SO gidi han. Java luon ki~m soat dude cac tinh huong d6. Vi du, cau true da lieu mang (array) va String trong Java la cac ldp dOl tucng va do vay c6 co che d~ tV kilKm soat cac chi so va cae gioi han stt dung cua cac phan ttt trong mango

24

L9P trinh huang d6i tUQng vai Java

+ Hon nira, Java k hdng su dung can tro (pointer) nen khong cho phep nhay tv do d@ thao tac tuy y a cac vi trt bAt ky trong b9 nho.

(iu) Th.uc h.ien. da luo"ng (multithreads)

+ Web 1a rn6i trudng rna d do co nhieu su kien co th~ xay ra dang thdi. Ngon ngfi S11 dung dJ l~p trinh Web phai h6 tr(i de; d~ dang cho nhieu Sv kien co th~ t.huc hien cung mot hie.

+ Java dap ling duoc tieu chuan da luang vi: Thu nhat n6 cung cap cac lop co the; t.huc hien nhu la cac luang duoc dieu kh ien rieng biet. Thu hai 18. Java tv t.huc hien duoc Sv ket hop giua cac pnan di bQ trong cac luang vdi nhau.

(v) Dam baa d(jng (dynamic)

+ Cac lop kh6ng nhat thiet phai dich va lien ket dJ tao ra mot tep IOn co th6 thuc hien ngay.

+ Thay vi do, hie thuc hien Java c6 the; xac dinh nhung lop nao can thi nap xucng, con nhirng lop khac c6 thJ dJ tren mang va sau d6 nap chung vao moi truong Java khi d.n thiet. BAng phuong phap nhu tren, cac ling dung Java co thJ gam nhieu lop duoc tS chuc puan tan tren mang.

(vi) Dam baa tuong d6i nhd va gon. nhe

+ Y wang co sd cua Java la ling dung co the; d~t a trung biro phuc vu (may chu) va sau d6 dude nap ve cac may tram khi c6 yeu du d@ thuc hien cong viec. Do vay, cac ling dung phai duoc t6 chuc sao cho du nno dJ viec trao d6i hieu qua (nap ve nhanh) va d~ S11 dung vdi moi nguoi.

+ Chuong trinh Java c6 thJ t6 chuc nho dude vi chung co thd t6 cnuc thea nguyen ly "don bfty", nghia la cac lop co the; t6 chuc thann cac goi (package) va chung se duoc nap ve khi c6 nhu cau.

(vii) Chu6n hod

+ Trang khi C/C++ 18. nhung ngon ngu chuan duoc xay dung t6t, nhung nhung b<} chuong trinh dich khac nhau lai c6 thJ cho nhirng ket qua khac nhau, Vi du, mot so bi) chuong trinh dich qui dinh rAng ham main() phai la ham c6 gia tr] tra lai thi mot so khac lai cho phep gan mac dinh kiJu int, hoac cac bQ chuong trinh dich khac nhau cho phep danh s6 byte khac nhau eho cac gia tri into

+ Java 18. ngon ngu chuan va luon cho cung mQt dang cai dat.

o T6 chuc cac dl! an ung dung v6'i Java

Cac t~p chuong trinh nguon Java chi chua dung mot loai la nhung rna ta ve cac lop

Chuong /I. GiCli thi$u ve lqp trinh vCli JAVA

25

rna chung ta da thiet lap, khong co cac bien toan cue, khong c6 ham mau (prototype). M9t s5lop co the; t6 chuc thanh cac g6i nhu la cac h~ thong can. Khi mot ldp muon S\1 dung nhung ldp duoc d(it trong mot g6i nao d6, vi du khi cAn Stl dung cac ldp dt; ket noi mang, chung ta phai nhap g6i chua chung la g6i java. net vao t~p chua cac lop ling dung.

Q Bt} JDK (Java Developer Kit)

Hien nay c6 nhieu moi truong h6 tro dJ p hat triJn phan mern vdi Java nhu: Visual J++, Symatec's Cafe, Borland JBuilder, JDK, V.v. B9 JDK do Sun cung c:1p thuc hien dua chu yeu trcn cac lenh don duoc nhap vao hi cac dong lenh va kha don gian, tien lei, JDK dude sl't dung ph6 bien con boi Ie mui nguoi c6 thJ de dQC duoc til Web Site: http://java.sun.com r 1]. B9 JDK cung ci'lp cac cong cu va cac chuang trinh sau:

1. javac

Chuong trinh dich chuyen rna nguon sang rna byte.

2. java

BQ thong dich: Thuc thi cac ung dung dQc lap, cac tep tin .class true tiep.

3. appletviewer B9 thong dich: Thuc thi cac ling dung nhiing (java applet) hi t¢p tin HTML rna kh6ng can S\1 dung trinh duyet nhu Nestcape, hay Internet Explorer, v. v.

4. javadoc

B9 tao tai lieu dang HTML hi ma nguon cung cac cnu thich ben trong.

5. jdb

H9 ga 16i (java debugger) cho phcp thuc hien tung dong lenh, diJ.t diJm dung, xem gia tri cua cac bien, v.v.

7.javap

B9 tao l$.p header cua C va eho phep chuang tri nh C goi cac phucng thuc (ham) cua Java va nguoc lai.

Trinh dich nguoc Assembler. Hi@n thi cac phuong thuc, du: li¢u truy nhap duoc ben trong cua t¢p tin .class da duoc dich va hi@n thi nghia cua byte code.

6. jauah

,. ,.". II)

2.3. CAC D~NG CHUONG TRINH UNG DVNG CUA JAVA

C6 ba loai chuong trinh c6 thJ phat tri@n voi Java:

• Cac chuong trinh ling dung dQc lap,

• Cac chuong trinh ling dung nhiing (applei),

• Cac chuong trinh ket hop ca 2 loai tren,

26

L¢p trinh huang doi tU<;lng vai Java

B(ji vi Java Ia ng6n ngfr l~p trinh huang doi tuong nen chuong trinh Java la tap cua mot hay nhieu lop d6i tuong. Moi tep chuong trinh nguon Java c6 th~ chua mot hay nhieu dinh nghia lop va ten cua t~p phai trung vdi ten ciia ldp cong khai va c6 duoi la ".java". Moi dinh nghia ldp trong tep nguon khi dich se dude dich va luu tru sang cac tep rieng trung ten vdi ten ldp va c6 duoi ".class". Tat ca cac lop phai duoc dich truce khi thuc hien.

D~ viet chuong trinh Java chung ta c6 th& si1 dung nhirng h~ soan thao ph6 dung nhu NotePad, WordPad, TextPad, Jereator v.v. H~ soan thao don gian va thich hop nhat co le la TextPad. BQ.n c6 th~ nl:1-p version mdi nhat ella TextPad til dia chi cua Web Site tren Internet: http://www.texlpad.com, nap Jereator ttt http://ww\ll.jerefltor.com.

Sau day chung ta xet rriau chung d~ phat trii£n cac loai chuong trinh ung dung voi Java.

2.3.1. CHUONG TRINH LING DVNG DOC L~P

Chuong trinh ung dung dQc l$.p Ia mot chuong trinh thea nghia thong thuong cua chuong trinh: t~p chuong trinh ngucn rna sau khi dich c6 th~ thuc hien true tiep.

D~ tao l$.p mQt chuong trinh ung dung dQc lap, chung ta phai dinh nghia mot lop co chua rnQt phuong thirc d~c biet ten la maini). Chucng trinh dQc lap biit dftu va ket thuc thuc hien (j mainO gi6ng nhu trang chuong trinh C/C++.

Khi xay dung mot ung dung dQc l~p can luu y:

L Tao l$.p mot ldp duoc dinh nghia bdi nguoi sv. dung c6 phuong thuc maini) goi la ldp chinh va dam baa n6 duoc dinh nghia dung thea rnAu qui dinh;

2. Ki~m tra xern lieu tfjp chuong trinh c6 ten trung vci ten cua lop chinh va duoi ".java" hay kh6ng;

3. Dich ~p chuong trinh d~ tao ra cac ~p rna byte code v6i. cac duoi ".class" tirong tillg;

4. S-lt dung chuong trinh thong dich cua Java d@ chay chuong trinh da dich.

Vi du 2.1. Chuong trinh ling dung dQc l~p.

Bai toan: Xay dung lop CharStack la cau true Stack va ling dung d@ dao nguoc cac xau ky tu,

II StandaloneApp.java

public class StandaloneApp{

public static void main(String args[l){

Chuong II. GI6i thi~u vi! IQp trinh v6i JAVA

27

CharS tack stack = new CharStack ( B 0) i /1 T'.l0 ra d6i nrong stack

String str = "maN teiV ,ioN aH" i IIT~o ra I xau

int leng = str. length () ; 1/ SO ky t1,1 trong xau

System.out.println("Dao nguoc day ky tu");

for(int k = 0; k < leng; k++) stack.push(str.charAt(k)) ;

whi Le (! stack. isEmpty ()) 1/ Lay fa tir stack theo thu W dao nguoc system.out.print(stack.pop());

II Dua vao stack

System.out.println() i

/1 Xu6ng dong

class CharStack {

private char[] stackArraYi private int topOfStacki private static int counter; II Toan tu tao l~p d6i nrong

public CharStack{int capacity) { /1(2)

/1 Mang cac ky tl!

/1 Dinh cua stack

II (1)

stackArray = new char [capacity) ; topOfStack = -1i

counter++i

}

public void push(char e) {stackArray[++topOfStack] = ei} public char pop() {return stackArray[topOfStack--] i} public char peek() {return stackArray(topOfStack] i} public boolean isEmpty() {return topOfStack < Di} public boolean isFull{) {

return (topOfStack == stackArray.length - 1) i}

T~p chuong trinh StandaloneApp co ten trung voi ten cua lop StandaloneApp, trong d6 c6 ham maint). Ham nay luon e6 dang:

public static void main(string args[]){ /1 Nqi dung thirc bien ella clurong trinh

ThuQc tinh public cua main() eho biet la ham nay duoc phep truy nhap doi vdi moi ldp tit ben ngoai cua ldp StandaloneApp va cho phep goi d~ thuc hien bdi chuong

28

lQp trinh huang doi IUQng vai Java

trrnh thong dich Java. Til kh6a static khai bao ham nay phu thuoc van ca lop, khong phu thucc van deli tuorig cu th@, do vay khi thuc hien khong dn phai t00 lap dc"'li tucng ct@ goi nhung ha m nhu the. Til void eho biet ham main() kh6ng can k8t qua tra lai. M9t dicu can luu y nua 13. ham main() co cac d6i sf{ la mang cac xau (deli tuorig) args[] cua String.

Trang chuong t.ririh t.ren con dinh nghia \(jp thli ha i la CharStack. Lop na~' c6 cac thuoc tinh: ma ng cac ky tu charl] stuclcArray, bien ki@u ini topOfStach va b9 clem stl ky tu counter trong xiiu. i\lGi k hi mot d6i tuong cua ldp CharStack duoc tao lap thi toan tii tao lap (con duoc goi IS. cau tii) Wong minh (2) (duoc di nh nghta bdi nguoi slt. dung) thuc hien d~ gan cac gia tri cho cac tham so thea yeu cau cua bai toano

Djch Va thuc hi~n chircnq trinh StandaloneApp.java

Chucng trinh nguon Java c6 th€ Slt. dung chirong tr'inh dich javac cua be) JDK: javac StandaloneApp.java

Ket qua cua lenh dich t.ren 18. hai t¢p StandaloneApp.class, CharStach.class chua mil. byte code cua hai ldp tuong ling. Nhirng t¢p lop da duoc dich c6 th~ thuc hicn voi chuong trinh thong dich java nhu sau:

java StandaloneApp

Ket qua t huc hien cua chuong trinh:

Ha Nai, viet Nam

Lute y:

./ Khi thuc nien voi Java thi chi d.n viet ten lop chua ham maint) va kh6ng can dua them duoi .class,

./ Khi soan thao chuong trinh nen tao ra mot thu muc rieng, vi du c:\users\Lan d6 ghi cnuong trinh nguon (StandaloncApp). Ta't ca nhung tep ldp (.class) 08U duoc tao ra a thu muc chua chuong trinh ngutin,

./ Phai chi ro thu muc chua cac chuong trinh dich, thong dich javac.exe, jaua.exe.

Thuong cac chuong trinh nay duoc cai d~t va duoc luu a thu muc, vi du c:\jdkl.3\bin \java .

./ M9i lop trong Java deu mac dinh xem la lop can cua lop Object duoc xay dung san trong g6i java. lang va g6i nay cling duoc xem la mac dinh Slt. dung rna kh6ng cAn nhap (import) vao nhu cac g6i khac khi srt dung cac lop chua trong d6.

Chuang /I, G;Oi th;~u ve IQp tTinh vo; JAVA

29

2.3.2. CHUdNG TRiNH UNG DVNG NHUNG APPLET

Applet la 10::.>i chuorig trinh Java dac biet rna khi thuc hien phai duoc nhung vao chuong trmh ling durig khac nhu cac trinh duyet Web Browser, hoac appletviewer CUrl ,JDK. Cling don luu y IS. hau het cac trinh duyct Web Browser: Internet Explore deu ho tro u@ thuc hien ,Java Applet.

Sau day chung ta xay dung mot applet ten la AppletApp t.huc hien Netscapc dao nguoc day cac ky tu nh U chucng tri nh ling dung dQc l*p iJ vi du 2.1.

Vi du 2.2 .• Java Applet

Bai totin: Nhi$m vu tuong t1.;i nh u hai toan d vi du 2.1 nhung thuc hien theo applct /1 ApplerApp.java

import java.applet.Applet; import java.awt.Graphics;

II Nhap thu vien chua lop Apple!

II Nhap ihu vien chrra lop Graphics

II Moi chuong trinh applet deu phai mo rong (extends), ke thira tir lap Applet public class AppletApp extends Applet{

CharStack stack;

String dayGoc, dayNguoc;

II Nap chong lai ham initt) M thuc hicn khi n<:lp va thuc hien applet

public void init () { II (l)

stack ~ new CharStack(80);

dayGoc ;;= new String ("maN tei V ,ioN aH") ;

in t 1 eng 0= dayGoc. length ( ) ; II SO ky II;! trong xau

II D~t cac ky W cua dayGoc vao stack de' sau d6 i<lY ra theo thir tl.f ngiroc lai

for{int k ;;= 0; k < leng; k++)

II Dua van stack

stack.push(dayGoc.charAt(k)) ;

1/ DQc ra tit stack thee thu {I,\' dao nguoc va hru vao dayNguoc

dayNguoc = new String(); while (!stack.isEmpty()) dayNguoc += stack.pop(); }

II Xfm moi rong

II Nap chong ham painu) d6 hien thi (ve) cac thong bao cua applet

public void paint (Graphics g) ( H (2)

g.drawString("Day ky tu dao nguoc:", 25, 25); g.drawString(dayNguoc, 25, 45);

}

30

lQp trinh huang doi tuc;mg vbl Java

}

class CharStack {

private char[] stackArray; private int topOfStack; private static int counter; II TOlin nr tao lap d6i nrong

public CharStack(int capacity) { stackArray = new char [capacityl i topOfStack = -1;

counter++i

1/ Mang cac ky til // Dinh cua stack

}

public void push(char e) {stackArray[++topOfStackl = ei} public char pop() {return stackArray[topOfStack--l i} public char peek(} {return stackArray[topOfStack] i} public boolean isEmpty() {return topOfStack < Oil public boolean isFull(} {

return (topOfStack == stackArray.length -I) i}

}

Lop Applet (ten dfty dujava.applet.Applet) trong thu vien cac ldp Java chuan (a g6i jaua.applet) cung cap khu6n dang va cac chuc nang chinh d§ phat trien cac applet. Lop AppletApp rna r9ng lop Applet nen no ke thua tAt ca cac chuc nang cua Applet. Trang lop AppletApp co hai ham thanh phan: initi), paint() duoc ke thira tit lop Applet nhu:ng dude nap chong d@ thuc hien viec dao nguoc xau va hi@n thi thong tin cua applet duoc tao ra tren man hinh. Hai l~nh import a dau chuong trinh lam nhiem vu nhap hai goi thu vien Java chua cac lop Applet va Graphics. Chu y thay a day ham mainO la kh6ng can thiet doi vdi applet.

Trude khi di tim hieu nguyen ly heat dQng cua cac applet, chung ta hay dich va chay thu vi du tren,

Djch va ch~y chU'dng trlnh AppletApp

Dich chuong trinh AppletApp thuc hien hoan toan giong nhu dOl vdi chuong trinh ung dung dQc lap a vi du 2.1.

javac AppletApp.java

Ket qua cluing ta cung co 2 t~p ldp AppletApp.class va CharStack.c1ass.

Chuong II. Gioi thi~u ve IQp trinh v6i JAVA

31

Chucng trinh applet khong th~ thuc hi~n true tiep thong qua chuong trinh thong dich java nhu doi vdi chuong trinh ung dung dQc lap. Chuong trinh applet phai dtroc dua vao trang tu lieu dinh dang HTML (HyperText Markup Language) d~ sau d6 nap duoc xucng thong qua Web Browser hoac appletviewer cua JDK.

'I'ep HTML chua cac thong tin tuong ung v~ ten t~p lop irng dung applet va nhilng thong tin khac can nap applet xuong d@ thuc hien. Thong tin toi thi~u can phai co doi voi lop applet la:

• Ten cua t~p lop applet,

• Kfch cd cua applet tinh thea pixel

Vi du: <applet code = "AppletApp.class" width = 200 height = 300 >

</applet>

T~p nay dude soan bang h~ soan thao ba't ky va dU<;Jc ghi voi ten goi AppletApp.html. Tep AppletApp.html co th~ 81'1 dung Web Browser d~ chay hoac s1'1 dung appletviewer duoc JDK cung cap nhu sau:

appletviewer AppletApp.html

Ket qua thuc hien cua chuang trinh applet:

Appt<ot-, Day k"y tu dao nguoc:

H$I Nei, Viet NafTl

Apptet starteQ,

Hinh 2.4. Thuc hi¢n chuang trinn applet voi chuang trinh thong dtch appletviewer.

Chu trinh hoat di?ng cua applet

Chuang trinh ung dung applet duoc thuc hi~n nhu sau:

• Khi ffiQt applet duoc nap va chay bdi Web Browser thi no se gl'.ti thong diep init() cung voi cac du: lieu, kich thuoc cua Window d~ chuong trinh applet khci d9ng.

• Khi biit dtiu thuc hien, Web Browser thong bao cho applet biit d:1u bang each goi phuong thuc start().

• Khi roi khci trang Web c6 chua applet thi chuong trinh applet nay nhan duoc thong di~p stop() d@ dung chuong trinh.

32

lQp trinh huang d6i tuc;mg vai Java

Hoat dong cua chuong trinh applet duoc mo ta nhu trong hinh 2.5, trong d6:

+ initi): Phuong thuc nay duoc goi khi applet duoc nap Ifin dAu va duoc xem nhu Ia toan ttl tao lap cho applet,

+ start(): Ducc goi khi applct bat diu thuc hien, xuat hien khi: applet duc;lc nap xuong,

applet duoc duyet lai.

+ stop(J: Duoe goi khi applet dung thuc hien, nhung chua bi x6a khoi b9 nho,

+ destroy(): Duoc goi ngay truce khi applet ket thuc, khi trmh duyet Web Browser W d6ng lai va applet bi x6a khoi b9 nhd,

Trinh duyet Web Browser tim chircnq trlnh applet

-----i~ .. ~

DUy$t tren trang web

trang web

Applet dl19'c huy

-4---- destroyt)

, 1 .

: Thoat khoi browser :

1 ----- ~_I

Hill}, 2.5. Chu trinh hoat d¢ng eua applet.

..,? ::;:: _ A

2.3.3. CHUONG TRINH (fNG DUNG o DANG APPLET LAN DANG DOC LAP

.. I • 'II •

Java cho phep xay dung chuorig trinh chay duoc ca d Web Browser Iftn nhu m(>t ung dung dQc lap. MQt chucng trinh nhu thE!' phai:

>- Dinh nghia lop ung dung mo rong, ke thua tu lop Applet, .,. Trang lop ung dung phai co ham maini).

Chuong II. GiOi thi~u ve IQp tr1nh vOi JAVA

33

Vi du 2.3. Chudng trmh chay duoc ca voi Web Browser va chay dQc lap import java. awt . Graphics i // XinChao.java

import java.awt.Framei

import java.applet.Appleti

public class XinChao extends Applet{ public void init(}{

resize (200,160) i

// Dat lai kich tluroc

}

public void paint (Graphics g) { g.drawString("Xin chao cac ban!D, 60, 25};

1/ Ham maini] dam bao chuong trinh se chay diroc doc lap public static void main(String args[]) {

XinChao h = new XinChao () ; // T<;lO ra m9t dOl tuong cua XinClJao h i Ln i.t I l ,

Frame f = new Frarne("Chao Mung va AppletD}; f . re s i z e (200, 160) i

f.add("CenterD, h);

f. show () ;

}

Chucng trinh nay si't dung lop Frame d5 tao ra khung Cd 200 x 160 khi no chay dQc lap, Chi tiet hon vo db hoa va cac chirc nang cua Frame se ducc de cap chi tiet d die chuong VII.

Luu y: Ta't nhien d@' chirong trinh XinChao chay dude vdi Web Browser thi phai dua VaG tep HTML (t~p XinChao.html) tuong tu nhu vi du 2.2.

Tom lai chuong trinh viet bAng Java co th@': ~ La cac ung dung doc lap,

y La cac chuong trinh ling dung nhiing applet, y Hoac ket hop ca. hai loai tren.

Tuy nhien giua ling dung dQc lap va applet cua Java cung co nhieu di§m khac nhau vt each khai baa va t6 chtrc thuc hien nhu trong bang sau:

3.LTH-A

34

19p trinh huang d6i tUQng vai Jove

Vng d~ng d¢c lap -I
Java.Apple_t ------i
Khaibaa La lap con cua bat ky lop nao trong cac Phai la lop con cua Applet
g6i thu' vien CaG lap
Giao dien do hoa TUy chon Do trinh duyet Web quyel dinh
Yeu cau b9 nho 89 nno loi thi~u 89 nho danh cho ca Irinh duyet
va applet d6
Cach nap chironq Irinh Nap b§ng dong l$nh Thong qua trang Web
Dir lieu VaG Thong qua cac Iham 56 tren dong I$nh Cac tham 56 di;lt trang tep HTML
gom dla chi, klch truroc cua trlnh
duy$t
Cach trurc thl/c hi$n Mcihoat d~rig diroc b~t oau va ket thuc d G9i cac ham: init(), start() , stop(),
main() nhlf Irong GIC++ destroy(), paintO
Ki~u Lmg d\,mg - vng dyng Iren cac may chu Server, Cac ling dl,\ng tren Web
- Gong cu phat tri~n phan rnern,
-
- Vng d\,mg tren cac may khach sAl T~P

2.1. Phan tich su giong, khac nhau cua qua trinh dich va chay chuong trinh trong ngon ngu lap trinh C/C++ va Java.

2.2. Neu nhung dac trung Cd ban cua ngon ngu Java, tai sao lai d.n si'i dung -Iava d& phat tri~n cac cnuong trinh ung dung,

,n

2.3. Chuong trinh ung dung Java d9C lap va cac ling dung nhung applet duoc thuc hien nhu the nao?

2.4. Neu each su dung cac chuong trinh cua JDK d~ dich va thuc nien cac chuong trinh ling dung cua Java.

2.5. Viet chuong trinh ling dung dQc lap d~ hien thi thong baa: "Xin moi cac ban lap trinh huang doi tuong voi Java!".

2.6. Viet chuong trinh ling dung applet d~ hi&n thi thong baa: "Xin moi eac ban lap trinh huang doi tuong voi Java!".

2;7. Viet chucng trinh d~ thuc hien duoc ca ling dung d¢c l~p Hin ling dung applet d~ hi&n thi thong baa: "Xin moi cae ban lap trinh huang doi tuong vci -Iava!".

2.8. So sanh su giong, khac nhau cua chuong trinh ling dung dQc lap va ling dung nhung applet.

3,LTH-B

CHuaNG III

" .. ~ ??

CAC THANH PHAN co sa CUA JAVA

Chuong III trinh bay nhung tnanh phan co sa cua ng6n ngu l$.p trinh Java, ki~u nguyen thuy, cac phep toan va cac bi~u thuc tinh toan,

, At.,. .,..,

3.1. CAC PHAN TU CO SO CUA JAVA

Giorig nhu cac ng6n ngu lap trinh khac, ng6n ngii l~p trinh Java ducc dinh nghia

- bang tap cac qui t~c dfrn xuat cua van pham cho phep ki6m tra xem cac cau true duoc xay dung t-u: cac phan tit cua ng6n ngu c6 hop l~ (chinh xac v~ mat cu phap) hay kh6ng va thong qua cac dinh nghla ve mat ngil nghia del ki~m chung y nghia cua nhirng ca'u true do.

£)jnh danh (Ten QQi)

Ten goi cua cac thann phan trong chuong trinh duoc goi Ia dinli danh (Identifier). Dinh danh dude S11 dung d~ xac dinh cac phan ttt nhu bien, ki&u, phuong thuc (method) hay con goi Ia ham, doi tuong, lop, v,v,

Trong Java dinh danh la mot day cac ky tu g6m cac chii cai, chil s6 va mot so cac ky hieu nhu: ky hieu gach dudi n6i cau '_', cac ky hieu tien t~ $, 't, £, C, va kh6ng duoc bit adu bang chu so'.

Luu y: Java phan biet chil thuong va chu hoa, vi du Hoa va hoa la hai dinh danh khac nhau. D9 dai (so ky tv) cua dinh danh trang Java ve ly thuyet 13. khorig bi gioi han,

Vi du cac dinh danh sau la hdp l~: so_nguyen, $My, danh_saeh12, HocSinh, con nhirng tU sau kh6ng ph iii la dinn danh 24gio, s6'_nguyen, Hoc-sinh.

Xu the chung hien nay la nen s-Lt dung each d~t ten thea mot chuan nnat dinh d~ de phan biet duoc cac loai khac nhau cua cac tha nh ph fin S\1 dung. Chung ta qui uoc each d~t ten thong nhat nhu sau:

+ Dinh danh cho cac lop: chii ctii <fdu cua moi tit trong dinh. danh <flu viet hoa, vi

36

LQp trinh hllong d6i tllQng vOi Java

du MyClass, HocSinh, KhachHang IS. dinh danh cua cac lop.

+ Dinh danh cho cac bie'n, phucng thuc, doi tuong: chit ctii aau cua m6£ til trong dinh. danh ac"u viet hoa tru til dau tien, vi du my Class, hoc Sinh, khachHang IS. dinh danh cua cac d6i tuong (bien) thuoc cac ldp MyClass, HocSinh, KhachHang tuong ling.

Cae tit kh6a

Cac til: kh6a ella mot ngon ngu IQ_p trinh la nhung dinh danh dinh sAn dUQc dinh nghia truoc ella ngon ngu va kh6ng th~ Stl dung cho nhirng thuc th6 khac. Cac tit kh6a cua Java e6 th6 chia thanh chin nh6m.

1. To' chile cdc ldp package

import

2. Dinh. nghia cdc lap

interface

class

extends

implements

Xac dinh mot goi se chua mot s6' ldp d trong t~p ngu6n.

Yeu diu mot hay mot s610p a cac g6i chi dinh cftn nhap vao d6 sir dung trong ling dung hien thci.

Dinh nghia cac bien, hang, phuong tnuc chung nhu 13. giao dicn co th@ chia se chung giua cac lOp.

Dinh nghia tuy~n t~p cac thuoc tinh du lieu, phuong thuc roo til cac dac tinh va cac hanh vi cua tap cac doi tuong c6 quan ht) vdi nhau.

Chi ra mot lop la rod rfmg (ke tnua) cua mot kip khac, hay con goi la lop can ella lop cho truce,

Xay dung mot lOp moi cai d$.t nhimg phuong thuc tir interface xac dinn truoc.

3. Cae tit khaa eho ctic bien va cac zap

abstract Khai baa ldp truu tuong kh6ng c6 th~ hien cu th~.

Khai bao lop, bie'n dil lieu, phuong thuc cong khai c6 th6 truy nhap a moi noi trong h~ thong.

private Khai bao bien dil lieu, phucng thuc rieng trong tung lop va chi

cho phep truy nhap trong lOp d6.

public

protected Khai bao bien du lieu, phuong thuc duoc bao v~, cho phep truy

nhap a ldp chua chung va cac lop con cua lop d6.

static Dinh nghia cac bien, phuong thuc tinh cua ldp, dung chung cho t:3't d. cac doi tuong trong mot ldp,

synchronized Chi ra la a moi thdi di~m chi co m0t d6i tuong hoac mot lcp co

Chuang III. Cae thanh phon co so cue Java

37

volatile

th@ truy nhap den bien da lieu, noac phucng thuc loai do, nghia Iii chung duoc dong bQ hoa,

Bao cho chuong t.rinh dich biet la bien khai baa volatile c6 th6 thay d(li di bQ (tuy y) trong cac luang (thread).

Chi ra cac bien, pnuong tnuc kh6ng duoc tnay d6i sau khi da duoc dinh nghia.

Lien ket IUQt phuong thuc vdi rna dia phuong (native code), rna duoc viet trong nhung ngon ngu lap trinh khac n hu C chAng han.

final

native

4. eric ki{i'u nguyen thuy (don gian)

long Ki@u so' nguyen IOn voi cac gia tri chiem 64 bit (8 byte).

double

Ki@u s6' nguyen vdi cac gin tri chiem 32 bit (4 byte).

Ki6u so nguyen ngan vdi cac gia tri chiem 16 bit (2 byte). Kidu byte voi cac gia tri nguyen chiern 8 bit (1 byte). Ki@u ky tv Unicode, moi ky tv chiern 16 bit (2 byte).

Ki6u so thuc voi cac gia tri bi~u dien theo dang dau phay dong 32 bit.

Ki6u so tnuc chinh xac ga'p doi vdi cac gia tri bi@u dien thea dang dau phay dQng 64 bit (8 byte).

Ki@u logic vdi 2 tri: true, false.

Ki@u trong, sli dung cho nrumg ham kh6ng tra Iai gia trio

int short byte char

float

boolean void

5. Nhiing' tit khaa cho cdc giti tri va eric bisn.

this

Cia tri ki6u boolean (sai),

Gia tri ki§u boolean (dung). Bien chi tdi d6i tudng hien thai. Bien chi toi doi tuong d lop chao Chi ra doi tuong kh6ng ton tai,

false true

super null

6. Xu Ij ngoai I¢

throw, throws Eo qua mot ngoai l~ d~ xu ly sau.

try Thu thuc hien cho den khi g(ip mot ngoai l~.

catch Don nhan m9t ngoai l~.

finally Tlnrc hien mot kh6i l~nh den cung ba't chap cac ngoai l~ c6 th@

,

xay ra.

7. Tao l(lp va hiem. tra cae dOL tuang

38

l¢p trinh hUClng d6i tU<;Ing v6i Java

instanceof

Tao l$.p mot doi tuong.

Ki~m tra xem mot d6i tuong c6 nam trong mot Wp hay mot interface hay kh6ng.

new

8. Dong ddu khiii'n

return

Chuyen die'u khi~n chuang trinh theo cac truong hop c"J case. Truong hop duoc tuyen chon thea switch.

Trudng hop mac djnh.

Thoat khoi cac chu trinh.

Lenh tuyen chon thea dieu kien logic.

Re nhanh thea dieu kien nguoc lai cua if. Tiep tuc thuc hien trong chu trinh.

Tra Iai gia tri cho cac phuong thuc.

Thuc hien m9t chu trinh.

Kct hop vdi do d~ tao ra mot ehu tri nh.

Chu trinh for vdi cac budc lap thuong Ia xac dinh,

switch

case

default break if

else

continue

do while for

9. Nhiing tit khaa chua aUfjc sll dr;ng
byvalue future outer
canst genetic rest
goto inner uar
cast operator Chu thich (Comment)

Trang cac chuang trinh thirong din phai c6 nhimg doan tu lieu giai thich cong viec hoac each tnuc hien d6 nguoi doc hi~u va ti~n thea doi, Nhimg phan giai th:ich d6 chi nharn lam tu lieu va duoc cac b9 chuang trinh dich bo qua. Java cung cap 3 loai cnu thich trong chuang trinh:

o Chu thich tren mot dong,

Q Cmi thich tren nhieu dong,

Q Chti thich trong tu lieu (javadoc),

Chu thich tren. m9t dong: TAt ca cac ky tu sau II cha de'n cuoi dong la chii thich.

II Tu day den cuoi dong 13. chu thich

Chu thich treri nhie'u dong: Giang nhu trong C, phan narn giua 1* va */la chu thich.

Chuang 11/, Cae thanh phon co so cue Java

39

/4' M()t chu thich ghi tren

n hieu dong

*/

Clu: thich trung tu lieu: Day la loai chu thfch dac biet duoc d~t van nhung cho thich hop trong chuong trinh d@ javadoc c6 th@ d9C va sa dung d@ tao ra t.u lieu dang HTML cho chuong trinh. Chung duoc dat VaG truce phan dinh nghia cac lop, interface, phuong thuc va bien. Pha n chu thich trong tu li~u duoc bAt d§u bang /** va ket thuc bang "I,

/**

* Lop nay cai dat giao dien Demo * Tac gia: Trftn An,

* Version 1. 0

*/

Luu. y: Kh6ng nen Slt dung cac chu thich long nhau, Vi du

// a day /* c6 su long nhau *J thi phan chii thich ben trong kh6ng xac dinh,

, ~ - - -,

3.2. CAC KIEU DU LI~U NGUYEN THUY

M6i ng6n ngu lap trinh d&u dinh nghia sAn mot so ki@u du lieu cd ban duoc goi la ki~u nguyen thuy.

Cac ki~u nguyen thuy cua Java duoc chia thanh 3 nh6rn: • Kieu nguyen gam cac kicu so nguyen va ki@u ky tu,

Cac ki@u so nguyen g6m: byte, short, int, long bi@u dien cho cac so nguyen.

Ki@u ky tu duoc th@ hien bang ki@u char, bi@u di~n cho cac ky tu rna Unicode gam cac chu cai, chu so va cac ky tu diitc biet. Ki@u char c6 65536 (21(,) ky tv trong t~p rna Unicode 16 bit. Mil cua 128 ky tu d~u cua tap Unicode hoan toan trung vdi rna ella 128 ky tl,i trong tap rna ASCII 7-bit va rna cua 256 ky tu dAu hoan toan tuong ung voi 256 ky t1,i cua tap rna rso Latin-I 8 bit.

• Kieu dtiu. phfi'y dong hay ki@u s6 thuc: L00-i nay c6 hai kieu float va double bi@u di~n cho cac so thap phan.

• Ki@u boolean: la ki6u boolean c6 hai gia tri true (dung) va false (sai). Hinh 3.1 eho chiing ta buc tranh khai quat ve cac ki@u nguyen thuy cua Java.

40

L¢p trinh huang doi tU(;m9 vai Java

Ki~u boolean (logic)

boolean

char

byte

short

int

long

float

double

Hinli 3.1. Cae kieu nguyen thuy trong Java.

i.e« y:

0/" Cac gia tri du lieu ki@u nguyen thuy Ia nguyen tU'. (kh6ng phan chia duoc) va kh6ng phai 13. cac d6i tuong .

./ Moi ki@u du lieu nguyen thuy c6 mien gia tri xac dinh va cac phep toan duoc dinh nghia tren cac gia tr] do nhu trong bang 3.1.

0/" Moi ki@u nguyen thuy co mot ldp bao boc (Wrapper hay con gQi lop nguyen thuy) tuong ung d@ s11 dung cac gia tri nguyen thuy nhu la cac d6i tucng. Vi du ung voi ki~u int c6 ldp Integer, ling voi char la Char, v.v.

.. .. ,.,

3.3. KHAI BAO CAC BIEN

Trang Java co bon loai bien:

• Cae bie'n thanh. phiin. la cac thanh phan cua lcp va duc;lc khdi tao gia tri moi khi mot d6i tuong cua lop duoc tao ra. N6i each khac, uit ca gia tri cua cac bien thanh phan se xac dinh trang thai du lieu cua mot d6i tudng.

• Cac bien tham chieu. dol. tuang (Object Reference) goi tilt la bien tham chieu va kieu lop con duoc goi la ki@u tham chien, la cac bien duoc s11 dung dg xli ly cac d6i tuong, Bien tham chieu phai duoc khai bao va khoi tao gia tri trudc khi sli dung.

HocSinh hs i /1 Khai bao bien hs tham chieu toi tap HocSinh.

Chuang III. Cae thanh phon eo so cuo Java

41

Luu j: khai bao nhu t ren kh6ng he tao ra d6i tur;ing cua lop HocSinh. No chi' tao ra bien hs d&' c6 th&' sAn sang luu tru nhung thong tin ve doi tuong cua HocSinh. Muon tao ra dOl tuong cho bien d6 thuong phai sU: dung toan tu: new. Co th~ kct hop khai bao voi viec khoi tao gia trj cho cac bien.

HocSinh hs ::: new HocSinh ("Lan Anh") i j/Khai bao ket hop d6 knoi 1,.10 gia If!

• Cae bien tinh. (static) cung IA cac thann vien cua lop nhung kh6ng phai dai dien cho tung doi tuong rna cho ca ldp.

• Cac bien ClJC bf) (local) la nhung bien duoc khai baa trong cae phuong thuc va trong cac khoi. Trong Java cac bien local phai duoc khai bao truce khi su: dung.

Bang 3.1. Cac qia tr] cua cac kie;u nguyen thuy

Ki~u £>9 r9ng Giil tr] eire tiliu Giil trj eve d<;li
duli~u (bits)
char 16 OxO Oxffff
byte 8 -128 (_27) +127 (27-1)
short 16 -32768 (_215) 32767 (215_1)
int 32 - 231. Ox80000000 + 231 _ 1, Ox7fffffff
long 64 _ 2G3 + 2G3 - 1
float 32 1.40129846432481707e-45 3.40282346638528860e+38
double 64 4.94065645841246544e-324 1.79769313486231570e+308 Bien luu tru cac gia trj cua cac ki&'u du lieu tucng ling. M6i bien co ten, ki&'u dli li~u va. gia tri dude gan, Viec khai baa bien 18 rilt don gian cung giong tU:dng tl,t nhu trong C/C++: ten ki~u va sau d6 khai bao cac bien dude each nhau boi dau phay ','.

char b, ei

float giaBan, dienTichi int tuoi, soCongTrinhi

Khi khai baa cling c6 th6 ket hop d~ khdi tao cac gia tri cho cac bien. int i ::: 10,

siSo ::: 50;

float pi ::: 3.1415F;

42

L¢p frinh hlIong d6i tlIQng voi Java

? ,. ".,.t

3.4. KHOI TAO GIA TRI CHO CAC BIEN

Cac gui tri rruic dinh. cho cdc bien thonli ph/in.

Moi ng6n ngu lap t.rin h dgu e6 qui djnh gan gia trj mac dinh eho cac bie'n khi da ducc khai bao va dinh nghla. Gia tri mac dinh eho cac bien ki6u dli lieu nguyen thuy trong Java duoc xac dinh nhu trong bang 3.2.

Bang 3.2. Cac gia tr] mac dinh

Ki~u dli' li~u

Gh'l tr] m~c dinh

boolean

false

char

, voooa o

byte, short, into long float, double

Tham chleu d6i tlJc;1ng

+O.OF, +0.00

null

Luu Y khi khai baa:

./ Cac bien ti nh trong ldp luon duoc khoi tao voi cac gia tri mac dinh neu chung kh6ng duoc gan gia tl'i tucng minh .

./ Cac bien thanh ph fin cung ducc khci tao mac dinh m6i khi dfli tuong cua lop c6 than h phan do duoc khoi tao neu chung kh6ng duoc gia trj tuong minh .

./ Bien tham chieu duoc gan mac dinh la null neu kh6ng tao lap tucng minh theo toan til: new va toan til: tao l(\p (constructor).

Vi du 3.1. II Light.java class Light{

II Cac bien tinh

static int boDem; flCilc bien the hien

int soWatts =100; II Gan nrong minh la l Ot)

1/ Gia tri 0 duoc gan mac dinh khi lap diroc nap

boolean bieuHien; /1 Gan mac dinh gia tri false

Str ing vi Tri; II Gan mac dinh gia tri null

public static void main{string args[]) {

Light bl = new Light ( ) i II Bien tham chieu local System.out.println{"Bien tinh boDem: " +Light.counter); System.out.println{"Bien thanh phan soWatts:" +b1.soWatts); System. OUt_. pI"" in Lln ("Bien thanh phan b i l2uHicn: ,. +b 1 . b i.e uli i c n ) :

Chuang III. Cae thonh phon eo so cua Java 43

_}

Sy'~tem,OUL,pr-iIlLln(" Bien thann ph an v i Tr L: "' +bl.viTr-l),

'}

Lop Light g6m bien t.harih phan tinh boDem ki4u int va cac bien thanh pharr soWatts kieu int, bieuHien ki4u boolean va bien tham chieu viTri kieu String (xau ky tu). Luu y die bien t'inh duoc khdi tao gia trj khi lop duoc nap Ian driu tien, con cac bien thanh phan duoc khoi tao gia tri mac dinh, neu khong gan Wong minh m6i khi mot dtii tuong cua ldp Light du'Qc tao ra.

~ ; ~ ,

3.5. CAU TRUC T~P CHUONG TRINH JAVA

Tep chuong trinh Java co th~ c6 cac phan duoc di;i.c ta_ nhu sau:

1. Dinh nghia mot g6i la tuy chon thong qua di nh danh cua g6i (package). Tat c8. cac ldp, cac interface duoc dinh nghia trong t~p chua g6i nay deu thuoc g6i do, Ne'u bo qua dinh nghia g6i thi cac dinh nghia d tep nay s6 thuQc VaG g6i mac dinh.

2. MQt s61~nh nhap import (0 hoac nhieu).

3. M9t so dinn nghia ldp va interface c6 the; dinh nghia theo thu tu bat ky, Cau true chuong trinh Java vi v$,y c6 th6 khai quat nhu sau:

II Filename: NewApp.java

// Ph1ln I: Tuy chon

// Djnh ngnia g6i package GoiNhaTruong;

// PhAn 2: (0 hoac nhieu han) II cac g6i can sir dung '.: import java.io. *;

1/ Phan 3: (0 hoac nhieu han)

/1 Dinh nghia cac lop va cac interface public class NewApp{ ... 1

class Cl ] .. ·1

interface I 11 ... \

II

class Cn 1 ... 1 interface 1m { ... \

L¢p trinh huang doi tuc;sng vai Java

LUll j:

,; T~p chuong trinh Java lu6n c6 ten trung vdi ten cua mot lop cong khai (lop chua ham main() ngu la ung dung d9C lap) va c6 duoi la .java.

,; Tep New App.j a va ncu la ch udng trinh ung dung d9C IQ_ p thi phai c6 mot lop e6 ten la NewApp va ldp nay phai co phuong thuc maini). Phuong thuc nay luon co dang:

public static void main(String args[]) { II Noi dung can thirc hicn cua c111tOTlg trmh irng dung

Noi dung cua phuong thuc main(J xac dinh tat cit cac cong viec de; h~ thong thuc hien.

,; Khi dich (javac) thi moi lop trong t¢p chuong t rinh sc duoc dich thanh byte code va duoc ghi thanh tep rieng co ten trung voi ten cua lop va c6 duoi .class, Nhirng ldp nay se duoc nap van chuong trinh Iuc thong dich va thuc hien theo yeu cau.

,; Trang chuong trinh ,Java khong c6 cac khai bao bien, ham tach biet khoi ldp va chi c6 cac khai baa va dinh nghia cac lop, interface. Nh.u thit chuong trinh Java dlive xem nhii lo. tap cdc lop, interface o« cdc do'i tliqng eua cluing trao do'i thimg diep uai nhau (bdng eric liii goi ham) de'thl/e hien. eric nh.iem V\1 eua ttng dung:

Vi du 3.2. Chuong trinh hi~n thi cac thong tin biet truce cua sinh vien. jlT¢p Display.java

import java.io.*i

1/ Nh;)p vao g6i java.io

class Display{ 1/ Xay dung lap Display M hien thi thong tin

public static void main (StT Lng ar-gs f 1 ) {

String hTen = "Lan Anh" i II Bien tharn chieu cue bo diroc grin tri diiu

int tuoi = 20 i 1/ Bien C~IC bo diroc gan tri dtiu

float diem = 8. SF i II Bien CI,lC bl) kieu float diroc gan tri dau so thuc

/1 Hien thi eric thong tin biet tnroc

System.out.println("Ho va ten: n + hTen); System.out.println(nTuoi: " + tuoi); System.out.println("Diem thi: " + diem) i

}

Tep chuong trinh tren co hai phan: phan 2 va phan 3. PhAn 3 co mot lop Display va ldp nay co mot ham maini). Trong ham maini) co cac bien eve b9 va sir dung ham System.out.prinilnt'Tlo va ten: " + hTen) la phucng thuc thuoc lop System duoc xay dung san d g6i java.io lam nhiern vu hi~n thi xau "Ho va ten: Lan Anh" lao kgt qua

Chuang /II, Cae thanh phon co sa cuo Java

45

cua phep ghep ('+') hai xau "Ho va ten: " voi xau trong bien tham chieu hTen (dol tuong cua lop String) tren man hinh (thiet bi vao/ra chuan). Ham System.out.printlnt) hien thi va xuong dong.

Dich chuong trinh Ilisplay.jaoa vdi javac chung ta d1.1Qc t~p Display.class va sau d6 Slt dvngjava d~ thong dich va hi6n thi thong tin neu tren.

Luu j: Cac hang S{) thuc trong .J a va d1.1Qe xern la gia tri (mac dinh) ki~u double.

float I = 3.14; II L6i VI khong nrong thich k ieu

Gia tri 3.14 dl1QC mac dinh la ki~u double va viec ga n gia tri c6 d9 chinh xac gAp doi eho bien kieu float se din tdi viec mat thong tin, do d6 h¢ thong se thong baa 16i. Vi the, hoac phai thong baa tuong minh la so thuc ki~u float (3.11 F):

float t = 3.14F:

hoac phai thuc hicn cp sang kieu (fZoat)3.14, float t = (f1oat)3.14;

Vi du 3.3. Chuong trinh doc vao 2 so va hien thi gia tri trung binh cua so d6. /1 T¢p Inputfrutput.java

import java.io.*i

class InputOutput{

public static void main (SUing Clr·gs l J ) { float x, Yi

String stri

/1 D9C dir lieu vao durri dang I xau

DatalnputStream stream = new DatalnputStream(System.in)i 1/ Hien thi thong bao "x =" va khong xuong dong

System. out. print ("X = ") i

try{ /1 Thir thuc hicn

str = stream. readLine (); II Doc vao 1 day cac chir so (xau)

} catch (IOException e) {str=" O. a" ;} II Don nhan khi gap ngoai I¢ /1 Chuyen day CiIC chii so v~ so thuc kieu float

try{

/1 Chuyen day cac ehii so sang gia tri kieu float

x = Float.valueOf(str) .floatValue(); }catch(NumberFormatException e) {x = a.OF;}

system.out.print("y = H); try{

str = stream.readLine(); }catch(IOException e) {str = "O.OFH;} /1 Chuyen day cac chir so ve so thuc ki6u float

46

lQp frlnh huang d6i tu<;mg voi Java

try{

y = Float.valueOf(str) .::oatValue(); }catch{NumberFormatException e) {y = O.OF;} system.out.println("Gia tri trung binh cong cua " + + " va " + y + " 1a n + (x + y) /2) ;

Van de nhap du li¢u vao tu ban phim tuong doi phuc tap trong chuong trinh Java vi muc dich chinh cua cac ling dung Java 1a d9C l~p vdi cac moi truong. D~ doc cac gia tri so vao cho chuong trinh, chung ta co nhieu each khac nhau. Cach tuong doi don gian la khai bao mot bien tham chieu thuoc lop String va bie'n tham chieu thuoc ldp DatalnputStream c6 dang nhu sau:

String str;

DatalnputStream stream= new DatalnputStream(Systcm.in);

Va'n de nhap du lieu van tit ban phim cung thudng gay ra nhieu ngoai 1~, nhu thay vi phai go cac chu so, chu Cal lai go vao ky hieu dieu khiJn hay vuot pharn vi xac dinh chang han, Vi~c ki~m scat cac ngoai l~ uao I ra trong Java c6 th6 thuc hien thea l~nh:

try{

str = stream.readLine();

}catch(IOException e) {str = "D.O";}

Lenh nay thuc hien nhu sau: D9c vao m¢t dong da lieu b~ng phuong thirc readl.inei) cua lop DatalnputStream va gan cho bien tham chieu str. Lap IOException lam nhiern vu xii Iy cac ngoai 1~ uao l ra. Khi gi,\p ngoai l~ uao lra thl gan mac dinh cho str z: "0.0". Cau l~nh try! '" lcatchi) Ia l~nh xli 1y ngoai l~ sc ducc trinh bay chi tie't d chuong 5.

; , ; """" ~ .,

3.6. CAe PHEP lOAN VA CAe BIEU lHUC

Nhiern V1,1 cua cac chuang trinh phan Ian la thuc bien cac phep tinh toan d§ xi11y dii' 1i~u. D~ l~p trinh dung cac yeu cftu tinh toan, chiing ta phai narn vtmg duoc cac thu' tv: uu tien cung nhu cac qui dc k€{t hop tinh toan ciia cac phep toan trong ng6n ngfi l~p trinh.

I' ..." ~ ",,' .A "1 ,.

3.6.1. THU Tl1 VU TIEN VA QUI TAC KET HOP THUC HIEN CUA CAC

" .. • ill

PHEP ToAN

Muc uu tien va cac qui tKc ke't hop cua cac phep toan can phai dUQc xac dinh d& tinh toan cac bi~u thuc. Cac muc uu tien va cac qui tKc ke't hQp cua cac phep toan trong

Chuang III. Cae thanh phon co s6 cuo Java

47

Java duoc xac djnh nhu trong bang ;3.3.

Khi sU: dung cac phep toa n chung ta hay hru y:

./ 86 uu t ien 18. t1 1$ nghich vdi muc uu tien thuc h ien trong cac bi~u thuc, Trong bi~u thuc, nhirng phep toan c6 so uu tien thap hon se duoc thuc hien truoc .

./' Nhung phep toa n c6 cu ng so uu tien trong mot bieu t huc se t.huc hien theo qui t~c ket hop tit trai qua ph ai hoac tit phai qua trai nhu bang 3.3 .

./' D~ thay d6i thu tv t huc hien thea y muon thi c6 th~ sl1 dung cap ngoac don (va ) giong nhu trong toa n hoc,

Bang 3.3. Cac phep toan trong Java

So uu Ten 9Qi Cae phap toan Qui t~e ket hop
tlem thuc hi~n
1 Phep loan 1 ng6i h~u 16 [} (Iham_so) exp++ exp-- Tlurc hien tV trai qua phal
(postfix)
2 Phep toan 1 ng61 tien 16 ++exp --exp +exp -exp - Thuc hien tlJ phal qua trai
(prefix) !
3 T<;1o I?p doi IVdng va ep kie:u new (type) ThljC hien W phai qua trai
4 Loai phep nhan . 1 % Thirc hlen W tral qua phai
5 LO?i phep conq + - Thuc hl$n tU trai qua phai
6 Chuy€ln d\eh « » »> Tht!e hi$n tlt tra' qua phai
7 Phep loan quan h$ < <= > Thuc hi$n W Irai qua phai
>= inslanceof
8 Phep so sanh dimg trurc -- != Tturc hien W trai qua phai
9 Phep va (AND) tren & Thuc hi$n tlt trai qua phal
bitwise/boolean
10 Phep ho~c 10<;1i tnr (XOR) " Trurc hi$n W trai qua phai
tren bitwise/boolean
11 Phep ho~c (OR) tren I Thirc hi$n tV trai qua phai
bilwi sa/boo lea n
12 Phep va (AND) logic && Thuc hien tlt trai qua phai
13 Phep hoac (OR) logic II Thuc hi$n W trai qua phai
14 Phep loan dieu ki$n ?: Thirc nlen W Ira; qua phai
15 cac phep qan = += -- .= 1= Thirc hi$n W phai qua trai
%= «= »= »>=
&= "= 1= 48

LQp trinh huang doi tuc;mg vai Java

,. ..!- _? ~ ... ~

3.6.2. CAC QUI lAC CHUYEN DOl KIEU

Ep ki~u

Java 13 ngon ngu rat chat vg kieu, n6 thuong ki6m soat chat che su tuong thich giua cac kieu trong cac ngu ca nh thuc hien ngay tu luc dich chuong trinh. Tuy nhien, mot sf{ ki6m soat cling chi' thuc hien duoc Iuc h¢ thong thuc hien, vi du nhu kicu (lop) cua cac bien tham chieu hay cac trucng hop thuc hien cac phep gan rna 2 toan hang khong tuong thich voi nhau ve kH~u (vi du, gan gia tri kiifu double cho bien ki@u int). Trang cac truong hop nhu the', ngtroi l~p trinh phai su dung qui d.c ep kiJu. Qui d.c ep ki~u co dang:

«type» <exp>

Luc thuc hien h~ thong se chuyen ke't qua tinh toan cua biJu thuc <cxp> sang ki&u duoc ep la <type>.

Vidv:

f loa t f::: (f loat) lOO.15D; II Chuyen s6 100.15 dang ki~u double sang float

t.e« y:

./ Khong cho phep chuyen d6i giua cac ki@u nguyen thuy voi ki6u tharn chieu, vi du ki@u double kh6ng thJ ep sang cac kiJu ldp nhu HocSinh duoc .

./ Ki&u gia tri boolean (logic) khong thJ chuyen sang cac ki@u du lieu so va nguoc

lai.

Vice chuyen deli kiJu thea qui tac ep kiJu nhu tren duoc gQi la chuyin do'i (ep) kie"'u tuimg minh, Java cung gi6ng nhu nhieu ngon ngu l!;tp trinh khac, ngoa i co che ep kiJu tuong minh can sv. dung co che' ep kie"'u khong tuitng minh (miic dinh), vi du c6 th@ gan ky tu char cho bien kieu into Sau day chiing ta xet hai each chuyen deli md rong va thu hep kieu.

Me, rQng va thu hep ki~u

D6i vdi cac ki~u du lieu nguyen thuy, gia tri cua ki6u hep hon (chiern so' byte it han) e6 th~ duoc chuy&n sang nhung ki&u rong han (chiem so byte nhieu hen) rna kh6ng t6n tha't thong tin. each chuyen ki6u do dUQc goi la md rqng kii'u. Java cho phep thuc hien md r9ng ki6u theo cac qui t:ic duoc rna ta nhu trong hinh 3.2.

byte --------7 short

---::~ int 3> long --------3> float --------3>double

char //

Hinh 3.2. Cdc qui tdc mo' rong kie'u,

Chuong 11/, Cae Ihcmh phon co so cue Java

19

Vi du:

char c ::: 'A'i

i nr. k ::: C i II rna rong kieu char sang kieu int (mac dinh)

Chuyen d6i ki~u thea chieu nguoc 19.i. tir kieu rong ve ki~u hep hon duoc goi 18. thu hep kit/u. Luu y la thu hep kie'u co thi dan toi nuit thong tin. Thuc te 18. moi 81.,t chuyen d6i ki6u dl1QC phep rna kh6ng phai la rna rong ki~u rthu hinh 3.2 thi deu la thu hop kieu. Nhu vay moi chuyen d6i giua char va hai kieu byte va short cimg lit thu hep kieu. Vi du:

int k = 10;

char c = (char) k , Irrhu hep kieu cua k v~ kieu cua e

Th6ng thudng viec thu hep ki~u phai stt dung qui tac ep ki~u tudng minh nhu tren. Cuoi cung chung ta cfmg cAn luu y ve ngu canh phai thuc hicn chuyen d6i kieu:

.:. Thuc hien cac phep gan d6i vdi cac bien ki@u nguyen thuy hoac kieu tham chieu, .:. Thuc hien cac loi goi ham (phuong thuc) vdi cac tham bien ki@u nguyen thuy

hay ki@u tham chieu,

.:. Thuc hien tinh toan cac bi@u thuc so' hoc,

.:. Ghep cac xau ket hop cac doi tuong cua lcp String va cac ki@u du lieu khac,

Sau day chung ta xet mot so' nhorn cac phep toan quan trong trong cac bi@u thuc,

3.6.3. css: PHEP loAN s6 HQC

Cac phep toan S6h9C dl1QC chia thanh hai I09.i:

1/ Cac phep toan 1 ng6i (don. nguyen): + (c(mg) va - (trii), cac phep d6i dau,

21 Cac phep twin 2 ng6i (nhj nguyen): * (nhan), / (chia), % (lay modul - phep chia

18'y s6du), + (cong) va - (tru),

Cac phep toan (totin. tu) so' h9C dude s-l'i dung d@ thiet lap cac bieu thuc toan h9C nhu trong dai so'. Cac toan hang (doL so) cua cac phep toan la cac bi@u thuc c6 gia tri ki@u so. Rieng phep + (ci)ng) con dl1QC S11 dung nap chong d@ ghep cac xau neu c6 mot toan hang la doi tuong cua lop String.

Luu j:

./ Thu tu ket hop thuc hien cua cac phep toan so' hoc don nguyen 1a ttt phai qua trai:

int val = - -20;

11(- (-20)) cho 20

Chu Y giira hai phep toan don nguyen la phai c6 dau each.

4_LTH-A

50

LQP trinh huang d6i tUQng vai Java

./ Thu tu ket h9P thuc hien cua cac phep toan so h9C nhi nguyen 18. tu: tra i qua phai:

int newVal = 10 % 4 * 4; int ~Val = newVal 1 5;

II «(10 % 4) * 4) cho g

II1lmc hien chia nguyen va cho ket qua la I

./ Liic th uc hien, cac toan hang phai duoc ttnh toan tu tra i qua phai t.rudc khi ap du.ig vei phep toano Khi 2 toan hang khac nhau ve kieu thi t huc hien chuyen d6i ki~u nhu trcn dil de cap .

./ Phep chia nguyen (2 toan ha ng dgu la ki&u nguyen) doi hoi so chia phai khac O.

int iv = 10 1 0;

II Sinh 16i ngoai 1¢ so h9C: Arithmeticfxceprion

./ Phep chia so thuc (ft nhat mQt toan hang ki&u s6 thuc) cho phcp chia rho 0 va ket qua phep chia cho 0.0 la INF (s6 ldn v6 cung) hoac -INF (so am v6 cung), hai hang dac biet trong Java.

float n , m = 4.5 10.0; n = -4.5 10.0;

II Cho m la INF II Cho n la -INF

./ Trong Java, phep chia lay so du % t.huc hicn dU(jc cit dui vdi so thuc.

float m = 11.5 % 2.5;

/I Cho m la 1.5

./ Khi 811 dung cac phep toan don nguyen d6i vdi cac d6i s6 ki~u byte, short, hoac char thi tru'dc tien toan hang phai duoc tfnh 1'6i chuycn vg kieu int va ket qua 18. kieu int, Vi du:

byte bl, b ::: 1;

II OK so 4 kieu int nhung eho phep thu hep ki~u mac dinh v~ byte

b::: 1 - b;

/I L6i VI 1 - b co ket qua kiEu int do v(IY thu hep kicu doi

/I hoi phai urong minh

bl ::: (byte) (1 - b); II Hoan loan dung

short h ::: 30;

/I OK: 30 kieu int chuyen v~ short (mac dinh doi voi hang nguyen

h::: h + 4;

/I Loi VI h + 4 eho ket qua ki~u int VI the khong th~ gan true tier

va II eho h ki~u short. Nhung,

h ::: (short) (h+4); !l1'.!i dung hoac eo th~ viet h ::: h + (short)4;

.#' , ,..~

3_6.4. CAC PHEP CHUYEN DICH «, », »>

Cac phep chuyen dich «, », »> thuc hien dich dang bi~u dien nhi phan cua toan hang tlnr nhat sang trai, sang phai solAn b~ng gia tri so nguyen cua toan hang thu hai. Cdc d6i s6' cua ch.ung luon la kdu nguyen.

4L TH·8

Chuang III. Cae thanh phon co sa cuo Java

51

Bi~u dien nh] phan cua cac so nguyen

Trude tien chung ta Iuu y rAng cac gia tri nguyen bi~u dien cho ca gia tr! dirong va gia tri am. Java S11 dung phdn bic 2 de' luu trii cae gia tri nguyen.

Cac bit trong dang bi@u dien nhi phan ella gia tr! nguyen (kieu char, short, int, long) duoc danh so tu phai qua trai va bAt dau bang O. Bit cao nhat la bit diu, 0 eho so duong va 1 cho so am.

Vi du: Bang 3.4 cho mot Sel bi~u dien phan bu 2 cua cac so chiem 1 byte. Luu y: Cach ttnh phan bu 2 thuc hien nhu sau:

Cho truce gia tri nguyen duong, vi du 41. Bieu dien nhi phan ella -41 duoc tinh nhu sau:

Bieu dien nhi phan

Cia trj thap phan

Cho truce gia tri

00101001 11010110 00000001

41

Lay phan bit 1

Cong them 1

Ke't qua 18. phan bu 2

11010111

-41

Tuong tv nhu vay dOl voi so am, lay phan bu 2 cua so am se duoc so duong.

Bang 3.4. Bi~u di~n nh] phan cca cac 56 chiern 1 byte
Gia tr] Ih~p Bi~u dien nh] phan 8 bit Gia tr] Hexa
phan
127 01111111 Ox7f
126 01111110 Ox7e
41 00101001 Ox29
2 00000010 Ox02
1 00000001 Ox01
0 00000000 OxO
-1 11111111 Oxff
-2 11111110 Oxfe
-41 11010111 Oxd7
-127 10000001 Ox81
-128 10000000 Ox80 52

lQp trinh huang dol tuc;sng voi Java

Phep dlch tral: «

a «n Dich U{t ca. cac bit cua a sang trai n liin, di~n so 0 van ben phai.

Vi du: int i ::: 12;

int re e i c-c n: 11192

Java 5tl dung 4 byte dt£ luu tru sf) nguyen do vay

12 « 4 ::: 00000000000000000000000000001100 « 4

::: 00000000 00000000 00000000 11000000::: 192

C6 thJ nhan thay moi l[\n dich sang trai mQt vi tri thi tuong duong voi viec Hi":y gia tr] truce d6 nhan vci 2 (voi dieu kien bit cao nhat dicn ra ngoai phai 13. 0). Trong vi du tren re ::: 12 ~ 24 ::: 192.

Khi doi s6 ben trai c6 kit£u byte hoac short thi se duoc chuyen sang kit£u tuong ling cua do'i 56 thu hai. Neu d6i sO' thu hai la int thi bit dau cua gia trj byte, short se dude md rong d@ di~n van nhung bit cao hon, vi d1.,1

byte b ::: -42; int rc ::: b « 4;

/111010110 /1 -672

Khi gia tri byte Ia -12 duoc chuyen sang ini thi bit dilu 1 se duoc dien vao cac bit cao hen nhu sau:

b«4 :::11111111111111111111111111010110«4

::: 11111111 11111111 1111110 1 01100000::: Oxfffffd60 ::: -672 ::: -42 * 2·j

Phep dich phai Va dii3n bit diu: »

a »> n Djch t8:"t ca cac bit cua a sang phai n Mn, dien bit diu vao ben trai.

Vi du: int i ::: 12;

int re ::: i » 2; 1/ 3

Java S11 dung 4 byte d§ luu trli 56 nguyen do v~y

12 « 4 ::: 0000000000000000 00000000 00001100 » 2

::: 00000000 0000000000000000 00000011 ::: Ox00000003 ::: 3

M!).t khac co th§ nhan thay moi IAn dich sang phai 1 vi tri thi tuorig duong vdi viec lily gia tri truce d6 chia cho hai (chia doi va lam tron duoi). Trang vi du tren: re ::: 12 /22::: 3.

Chuang III. Cae thonh phon co so cue Java

53

Khi d6i so' ben trai c6 ki~u byte hoac short thi se ducc chuysn sang ki~u tuorig ung cua dOl s6th(( 2. Neu d6i so thu hai la ini thi bit dau cua gia tr] byte, short se duoc fib rQng d~ di~n VaG nhirng bit cao hon, vi du

byte b:::: -42;

//11010110

int re= b » 4;

//-3

Khi gia tri byte la -42 duoc chuyen sang int thi bit dau 1 se dtiQc dien VaG cac bit cao hon nhu sau:

b»4 = 11111111111111111111111111010110»4

= 11111111 11111111 11111111 11111101 = Oxfffffffd =-3

Phep dich phai va dien bit 0: »>

a»> n Dich tat ca. cac bit cua a sang phai n Ian, dien 0 VaG ben trai.

Vi du: byte b = -42; 1111010110

int re = b »> 4; 11268435453 - khac ket qua tren rAt nhieu

Khi gia tri byte la -42 duoc chuyen sang int thi bit dau 1 se duoc di~n VaG cac bit cao hon nhu sau:

b »> 4 = 11111111 11111111 1111111111010110» 4

= 00001111 11111111 11111111 11111101 = OxOffffffd = 268435453

t.e« j:

./ Gia tri cua d6i so' ben phai ( a tren la n) luon la so' nguyen (duong) do vay d6i so' ben trai ( d tren Iii a) neu 1:1 byte hoac short thi phai dbi sang ki~u into

./ Kct qua cua die phep chuysn dich vi vay se luon Iii int (hoac la ki~u long neu d6i so' thu nhat Iii long).

, , , ? A

3.6.5. CAe PHEP GAN MO RQNG

Cac phep toan gan md rQng c6 cu phap dang:

<var> <op>= <exp>:

trong d6 <var> Iii bien, <op> Iii mot trong so' cac phep toan: +=, -=, *=, 1=, %=, «=, »=, »>=, &=, A=, I = va <exp> Ia bi~u thuc tuong ling vdi cac phep toan dil chon.

54

lQp trinh huang doi tUc;Jng voi Java

Cac phep gan SO hoc md rQng

DOl vdi cac phep gan so hQC mo rQng thi qui tiic cii phap tren tuong duong ngu nghla vdi l~nh sau:

<var>:: «type» {<var> <op> «exp»);

trong d6 <type> la cac kieu s6 va <op> IS. phep toan so hoc +, -, *, I, %. Bang 3.5 mo ta chi tiet hen cac phep gan so' hoc md rQng.

Bang 3.5. Cac pnep gan 56 hoc ma r¢ng

x 1= e:

x = (T) (x + (e)); x = (T) (x • (e»; x = (T) (x * (e»); x = (T) (x 1 (e»); x = (T) (x % (ej):

Ciu I~nh gan

Cho tn.Me kl'U s6T ella bie'n x va bi~u tmrc e

x += e;

x·= e;

x *= e;

x %= e;

Do qui dinh cac phep gan so hoc rud rQng co dang tuong duong vc mat ng-u nghla nhu tren nen thuc chat la da co 81,1 ep ki~u giua cac ket qua cua bi§u thuc d ve phai ve ki~u T cua bien x, Vi du:

int i:=: 5;

i *:=: i + 2; //Tfnh nhu la: i::: (int) (i * (i+2));

byte b ::: 3; /1 Cac hang nguyen eho phep thu hep kieu nhir mac djnh

b +::: 4; /IT{nh nhu la : b == (byte) ((jnt) b + 4);

b :=: b + 4; 1/ Sai VI ve phai co ke't qua kieu int con b kieu byte doi ep kieu

Cae phep gan logic md rQng

Cac phep gan logic rnd rQng duoc dinh nghla chi tiet nhu trong bang 3.6.

Bang 3.6. Cac phep gao logic rna r9ng

b 1= e:

b = (b & (e)); b = (b " (e)); b = (b I (e));

Cac '~nh giin

Cho b va bi~u thLi'c e kiE!u boolean

b &= e;

b "= e;

Chuong III. cec thanh phon eo s6 cue Java

55

boolean b 1 :::: false, b2 ::: false, b 3 :::: true;

b3 &:::: b3 & b 1 I b2;

// false vi b3::: ((b3 & b 1) I b2);

Cae phep giln md rQng tren bit (bitwise)

Cac phep gan mb rQng tren bit c6 dang ngtr nghia tuong tu nhu cac phep gan s6' hoc mb rong, nghia Ia ket qua cua bi~u thuc ben phai duoc ep v(} ki&u cua bien nhan kc't qua (ve trai). Nhirng phep nay duoc dinh nghla nhu trong bang 3.7.

Bang 3.7. Cac phep gfm ma r9ng tren bit

Cae I~nh gan

Cho T la ki~u nguyen ella b va bi~u thue e

b &= e;

b "= e:

b 1= e:

b = (T) (b & (e)); b = (T) (b " (e»; b = (T) (b I (ej):

int vO :::: - 42; char v l = 'r; //41 byte v2 :::: 13;

vO &= 15; //1 ... 1101 0110 & 0 ... 0000 I Ill::: 0 ... 0000 0110 (=6)

Dai vdi nhirng phep gan md rong tren bit duoc qui dinh nhu trong bang 3.7, do v$.y kh6ng d.n ep ki~u khi thu h9P ki&u.

Cac phep gan chuyin djch ma rQng

Cac phep gan dich chuyen mb rong: < <:::: , »:::, »>= diroc dinh nghla nhu trong bang 3.8.

Bang 3.B. Cac phep gan dich ehuyE§n ma r9ng

Cae I~nh gan

Cho T la ki6u nguyen cua b va bi6u thue e

b «= e;

b »= e;

b »>= e;

b = (T) (b <:< (e»; b = (T) (b » (ej): b = (T) (b »:> (ej);

Vi du: int i :::: -42; // Bi~u dien -42 a dang nhi phan pharr bu 2: 1...110 I 0110

56

LQp trinh huang doi tUQng vai Java

i »:::: 4;

111...11010110» 4 => 1...11111101 (::: -3);

byte a = 12;

a «= 5;

II Cho a = -128 VI a:::: (byte) (Cint) a« 5)

a ::: a «5; II Sai boi a« 5 la kitu int do vay doi hoi ep ki€u luang minh.

.. , ., ., J,. ,

3.6.6. CAC PHEP TOAN SO 5ANH DANG THUC

Cac phep toan so sanh <, <>, >, >= cua Java duoc dinh nghia gi6ng nhu trong cac ngon ngu :Q_p trinh khac (nhu C chang han). Trong do chi din luu y HI. 2 d6r s6' phdi Iii cdc bie"'u tluu: s6: Rieng phep so sanh dftng thuc (bang) thi phuc t<;J.P hon. Sau day cnung ta xet cac dang so sann dang tnuc trong -Iava.

So sanh d~ng truro tren cac gift tr] ki~u nguyen thuy: ==, !=

Cho truce hai toan hang a, b c6 ki~u dli lieu nguyen thuy,

a == b a va b co bang nhau khong", :J':-ghia la neu chung co cac gia trj kiifu nguyen thuy b~ng nhau thi cho ket qua dung (true), nguoc lai cho sai (false).

a ~= b a va b co khac nhau kh6ng?, nghia la neu chung c6 cac gia tri ki~u nguyen thuy khong bang nhau thi cho ket qua dung (true), ngudc lai eho sai (false).

Luu y: Ki@u cac d6i sO' c6 th@ la cac kieu sO' hoac ki6u boolean, nhung 2 doi so pnai luon c6 kieu tuong thich va sanh duoc voi nhau. Vi du «boolean value> == c) se khong hop l~ neu c e6 ki6u sf{. Tuy nhien neu bi~u thuc c6 nhieu phep == kct hop thi phai than trong va din cli vao thli tv thuc hien vi co th6 ta't ca cac toan hang deu c6 kieu s6 nhung bi6u thuc vlin kh6ng hop 1~, hoac nguoc lai khi cac d6i sO' c6 kieu khac nhau nhung van hop l~. Vi du:

int a, b, c;

a = b = c = 10;

boolean hl= a :::= b == c; II Sai boi phai thuc hien a == b cho gia If! true,

II sau d6 so vai c (gia If! s6) thi 2 d6i s6 khac kieu, boolean h11 = a == b =:::: true; II Lai hop l¢.

So sanh d~ng thirc tren cac tham chleu doi h.tc;1ng: ==, !=

Cho truce r va s la hai bien tham chieu, Cac phep so sanh d~ng thuc tren cac bien tham chieu dude xac dinh nhu sau:

Chuang III. Cae thanh phon co so cuo Java

57

r == s

Cho gia tri true neu r, s cung tham chieu tdi cung mot tri (d6i tuong), nguoc lai se cho gia tri false.

Cho gia tri true ne'u r, s kh6ng cung tham chieu toi cung mot tri (d6i tucng), nguoc lQ.i se cho gia tri false.

Hai phep toan nay dude S11 dung d@ kiern tra xcm hai bien co chi tdi cung mot d.6i tuong hay kh6ng.

r !::::: s

Luu. j: Cac toan hang phai c6 ki6u tuong thich (chuyen d.6i giua cluing diroc mac dinh), neu kh6ng thi phai thuc hien ep ki~u.

Vi du 3.4. So sanh qua tham chieu

class SV{ String hTen; int tuoi;

SV(String ht) {

1/ Toan IU tao lap d6i ttrong moi

hTen = hti

}

public static void main(String[] args) {

SV svl = new SV ("Lan Anh") i /1 Tao ra I d6i nrong moi SV sv2 = new SV ("Lan Anh" 1 i I/T':lo ra 1 d6i nrong moi

SV sv3 = new SV ("Tran Anh") ; /1 Tao ra 1 doi nrong moi

boolean t 1 = svl -- sV2; /I false

boolean t2 ::: svl -- sV3; SV sv4 ::: sV2;

boolean t3 ::: sV4 :::::: sV2; lllruc

1/ false

System.out.println(" tl ::: "
System.out.println(" t2 ::: "
System.out.println(" t3 ::: "
} + tIl i + t2); + t3);

}

~ ~.....",..... ...

3.7. TRUYEN THAM SO VA CAC LOI GQI HAM

Nhu phan d§.u chiing ta da de e~p, cac d6l tudng trong chucng trinh trao d6i vdi nhau bang each trao d6i cac thong di~p (message). Mt;t thong diep duac cai diJ.t nlut la lai goi ham (phuong thuc) trong chuong trinh, goi tdi ham thanh phan cua doi tuong d6i taco Nhiing ham tlnh c6 th6 goi voi ten ella lop. Cac tham so trong cac leri goi ham cung cap each thuc trao d6i thong tin giua d6i tuong g11i va doi tuong nhan

58

lQp trinh hUdng d6i tUQng Vdi Java

thong diep.

Cu phap cac lei goi ham c6 cac dang sau:

«Tham. cliisu dol, tuljng >. <Ten ham> (-cdanh. stich. tham bien hien. thai» <Ten lap>. <Ten ham tinh» (cdanh. stich. thani bien hien. thin»

<Ten ham> (e.danh. siich. tham bien hien. thai»

Vi du:

hinh'I'ron.ve/); II hinhTron In. d6i tuong cua lop HinhTron

int i = java.lang.Math.abs(-4); 1/ G9i day du ten cua lop Math

int j = Math.abs( -4); II Goi thea ten ella lop Math

someMethod(ofVa1ue); 1/ D6i nrong hoac lap kh6ng tuong minh

Trang lap trinh, chung ta da quen vdi khai niern danh sach. tham bien hinh thuc 1il danh sach cac tham bien duoc dinh nghia trang dinh nghia cac ham. Danh sdch. tham bien hi¢n thai la danh sach tham bien duoc truyen vao cho cac lei gni ham tuong img. Cac danh sach nay c6 th~ la rang. Hai danh sach hinh thuc va hien thai phai tuong thfch voi nhau:

./ So cac tham bien cua danh sach hmh thuc phai b~ng so cac tham bien cua danh sach hien tnoi.

,f Kiiu cua cac tham bien hien thoi phai tuong thfch vdi kiiu cua tham bien hinh thuc tuong ung, Ring 3.9 tom t~t each truyen cac gia tri phu t.huoc van kidu cua cac tham bien hinh t.huc,

Bang 3.9. Truyen them 56

KiEiu cua tham bien hlnh thue

Gia tf( dl1<;1c truyen

Cac kieu nguyen thuy

Gia Irl kieu nguyen thuy

Kieu lop (class)

Gia tri tharn ehieu

Kieu mang (array)

Gia tr! tharn chieu

Luu j: Trang Java, moi tham bien deu duoc truyen theo tham trj (passed by value).

Truyen CaC ghi tr] kie;u nguyen thuy

Khi cac tham bien hinh tnuc co ki~u la nguyen thuy thi gia tri cua cac bien duc;tc sao sang bien hinh t.huc trang cac Idi goi ham. Rdi vi ctic'bien hinh. thuc la qw bi) trong djnh nghia cua mot ham ne n moi thay d6i cua bien hmh thuc kh6ng anh huang den

Chuang 1/1. Cae th6nh phon co so cue Java

59

cac tham bien hi~n thi'ji.

Cac tham bien c6 th~ la cac bi~u thuc va chiing phai duoc tinh truce khi truyen van loi goi ham.

Qui 110C C huyen deli ki~u giua tham bie'n hirih thuc va hien thoi cimg giong nhu da dude thao luan a 3.6.2.

Vi du 3.5. Truyen cac gia tri nguyen thuy class KhachHangl{ II Lap khach hang

public static void main(String[] argl {

HangSX banh = new HangSX (l ; /I Tao ra mot d6i tirong

int giaBan = 20;

double tien = banh.tinh{lO,giaBan);

System. out. println ("Gia ban: " + giaBan); /1 giaBan kh6ng deli System. out. print In ( "Tien ban duoc : " + t ien) ;

}

}

/1 LOp Hang san xuat class HangSX{

double tinh(int num, double gia) { gia = gia /2;

return num * gia;

/1 Thay obi gia nhirng khong anh huang toi giaBan, /1 nhirng so tien viln bi thay obi thea

'Khi thuc hien chuong trinh se eha ket qua:

Gia ban: 20

Tien ban duoc: 100.0

Trang ham maint) cua lop KhachHang thuc hien: + Tao ra mot bien doi tuong banh cua ldp HangSX, + Dinh nghia bie'n thanh phan giaBan = 20,

+ GQi ham thanh phan tinhi) phan cua banh d~ tfnh so tien ban du<jC 10 chiee banh,

Mac du trang ham tinhO cua ldp HangSX dB. thay deli tham so hinh thuc gia nhung khi goi voi tham so hien thoi giaBan thi viec thay deli tren khong anh huang tdi gia tri cua giaBan.

60

LQp trinh huang d6i tuc;mg vai Java

Chung ta cling din luu Y la ki~u cua tharn bien hien thdi thu 2 cua ham tinh() la int, trang khi ki6u cua bien hinh thuc tucng ling Iii. double. Trude khi girl trj cua bien hien thoi duoc sao cho bien hinh thuc thi gia tri (so 20) kieu int phai duoc rnb r9ng sang double thea mac dirih. Co che truyen tharn bien doi vdi cac gia tri nguyen thuy eo th~ rninh hoa nhu sau:

Tharn bien hien thoi

double tien = banh.tinh(

giaBan

~);

I ,

~

Dinh. nghia ham

, , , I I I ,

, I I I

I ,

Tharn bien hi nh thuc ~ 20.00

, double gia ) {

double tinh(int num

Hinh :1.3. mo td co che truyen tham bien dUI VOl cac tri nguyen thu».

Truyen cac gia tr] tham chleu doi tLtc;sng

Khi bien hien thoi tharn chieu tdi clui tuong, thi gia tri tham chieu cua doi tucng se duoc truyen cha bien hinh thuc, Nghia la ca bien hinh thuc va bien hien thoi la hai ten goi khac nhau (bi danh) cua dOl tuong duoc tharn chieu toi trang lei goi ham. Do vay, moi thay clBi thuc hien doi vdi cac thanh phan cua doi tuong thong qua tharn bien hinh thuc cling se co hieu qua cii sau loi goi ham va tac dong len bien hien thoi.

Vi du 3.6. Truyen thea gia tri tham chieu l/KhachHang2.java

class KhachHang2 { II Lap khach hang

public static void main (String [1 arg) {

Banh banhMoi = new Banh() i

1/ T<;l0 ra mot d6i nrong (I)

Sys t em. out. pr int In ( n Nhoi thit vao banh truoc khi nuong : n + banhMo i . t hi t) ;

nuong (banhMoi) i /1 (2)

System. out. print In (" Thit cua banh sau khi nuong: II +banhMoi . thi t) ;

public static void nuong(Banh banhNuong) { fi(3)

banhNuong. thit == "Thit vir";

II Ngiroi rurong banh d6i nhan thanh thit vit

Chuang III, Cae thanh phon co so eua Java 61

banhNuong == null: II (4)

}

class Banh{

II Lop Banh

(5)

Str ing thi t = "Thit ga"; II Qui dinh ella hang lam nhan banh bang thit ga

Khi thuc hien chuong trinh se eho kct qua:

Nhoi thit vao banh truoc khi nuong: 111il ga Thir ella banh sau khi nuong: Thit vir

M9t doi tuong banhMoi ducc tao ra b (1) voi nhan nhoi "T'hit ga" nhir qui dinh a (5). Trang 16:i goi ham nuongt) d (2) gia tri tham chieu doi t.uong ella bien hien thoi banhMoi duoc t ruyen eho bien hinh thuc banhNuong ella ham nuongt) duoc dinh nghia d (3). Trang ham nay bien thit cua lop Banh bi thay d6i thanh "Thit vit". Nhfing thay d6i nay e6 anh huong tdi trang thai cua doi tuong duoc tham chieu. Nhung viec thay d6i ea doi tuong nhu d<)t banhNuong thanh null (khong e6 doi tuong) a (4) 19-i khong h6 e6 tac d(mg doi vdi dOl tuong tham ch ieu bci bien hien thoi.

Thurn bien hinh tlnrc

banhMoi: Ref(Banh)

sao gia tri tharn chieu va tao ra bi danh

I I I I I I

t

banhNuong:Ref(Banh)

:Banh

Ihit = " Thit 9a"

Tham bien hien thdi al Thuc hien 16:i goi ham

Tham bien hinh thtrc Ir--b-a-n-h-M-O-i:-R-e-f-'B-a-n-h-}--'

Sau 10i goi ham, gia tri cua tham bien hien thoi ky hieu eho cung doi nrong d5 bi thay d6i

:Banh

thit = " Thit vif'

I banhNuong:Ref(Banh) ~ -- -- -- -- ----- ---.,

Tharn bien hien thoi

bl Ngay sau khi thuc hien loi goi ham

62

l¢p trinh huang d6i tuc;mg voi Java

T6m lai, bie'n hinh thuc chi co th~ lam thay d6i trang thai (cac thanh phan) cua deli tudng duoc tham chieu tdi trong lei goi ham.

Truyen cac tham chieu theo mang

Mang (array) trong Java duoc xem nhu 18. d6i tuong. Cac phan t1.'i cua mang c6 th~ c6 kieu nguyen thuy hoac ki~u tharn chieu (ki&'u lap), Chi tiet vt mang chiing ta se xet a chuong sau. Sau day chung ta tim hi~u vt cd che truyen tham chien kieu m ang (cac tham bien la marig).

Vi du 3.7. Truyen cac tham chieu kieu mang II Loc.java

class LOC{

public static void main(String[] argsl {

int[] day = {8, 1,4,3, 2, 51;IIKhi1it~om<'l.I1gdayvag'lntridau II Hien tn] cac ph fin tu cua day tnroc khi loc

for tint i = 0; i < day. length; i++)

System.out.print{" "+ day[i]);

System. out. println (1 ; // Xuong dong moi

int maxlndex ~ 0;

J I LQe ra phan llr eire dai v~\ dira v~ cuoi

for tint index = 1; index < day. length; index++l

{

if (day [maxlndex] ~ day[index])

doiCho (day, maxlndex, index); II (I)

maxlndex = index;

1/ Hien thi day sau khi loc

for (int i = 0; i < day. length; i++) system.out.print(" "+ day[i]); System.out.println();

}

public static void doiCho(int[] bang,int i, int k){ /1 (2) int tg = bang[i] i bang[i] = bang[k] i bang[k] = tg;

Chuong III. Cae thanh phon co so cue Java

63

Kct qua cua chuang trinh sau khi thuc hien:

8

1

2

5

1

2

5

8

Trang phan djnh ng hia ham doiChoO a (2) hien hinh thuc bang I:) ki@u array (truing), Ham nay d119c goi trong ham mainO a (1), trong d6 bien hien thdi day cung Ia ki&u mango Vi trong -Iava cac Idi goi ham deu thuc hien thea tham tri (call-by-value) dai vdi ki@u nguyen thuy vi, tham chieu doi voi ki~u ldp nen ham doiChoO nhu tren la thay cl6i dU9C cac pha n ttt cua day (bien hien thoi).

Cac tham bien final

Tham bien hinh thuc co th~ khai bao vdi tu kh6a final dung t.rudc. Tham bien loai nay dU9C goi ta bien cuoi "trang", nghia la n6 khong duoc khoi tao gia tr~ (IS. trang) cho den khi no duoc gan mot tri nao d6 va khi eta duoc gan trj thi gia tri d6 la cuoi cung, kh6ng thay d6i duoc,

Vi du 3.S. Sl't dung tham bien final IlKhachHang3.java

class KhachHang3 { II Lop khach hang

public static void main(String[] arg) {

HangSX banh = new HangSX ( ) j II Tao ra 1 doi nrong

int giaBan = 20;

double tien = banh.tinh(lO,giaBan);

System. out. printIn ( "Gia ban: "+ giaBan) j II giaBan kh6ng dbi System. out. print In (" Tien ban duoc: " + t ien) j

}

/1 Lap Hang san xuat class HangSX{

double tinh(int num/final double gia) (fi(l)

gia = gia /2.0; 11(2)

ret urn n urn * 9 i a j 1/ Thay dbi g ia nhirng kh on g anh h irong toi g iaBan, II nhirng so tien viin bi thay dbi theo

}

Khi dich ham tinhi), chuong trinh dich se thong bao lei va kh6ng duoc phep thay d6i gia tri cua bien final gia trong djnh nghia ham nhu d (2).

64

lQp trinh hllang d6i tllQng vai Java

Cdc d6i s6' eua ch.uong trinh

Giong nhu chuong trinh C, chung ta c6 th& truyen cac tham sf} cho chuong trinh tren dong l¢nh, vi du:

java TinhTong 12 23 45

Chuorig trinh java thong dich ldp TinhTong d~ tinh t6'ng cac doi so' 12, 23, 45. Chuorig trmh TinhTong c6 th@ viet nhu sau:

Vi d\l3.9. Truyen tham so cho chuong trinh II TinhTong.java

class TinhTong{

public static void main{String args[]) { float s = a.OF;

for (int i = OJ i < args.lengthj i++)

s += Float. valueOf (args [i] ) . f loatVal ue () j II Cnuyen day chu so thann so system.out.print(nTong cua " + args[O]); for lint i = 1; i < args.length; i++)

system.out.print(G + ff + args[i]); System.out.println(" = ff + s);

}

Khi thuc hien chuong trtnn cho kCt qua

Tong cua 12 + 23 + 45 ::: 80.00

3.1. Nhung tir sau c6 p nai Ia dinh danh hay khong?

al a4z, bl fin2, c/ _class,dl My$lOO

3.2. Day 1* .. , II ... *1 c6 phai 1;\ chii thich hay khong? tai sao?

Nmmg lenh nao trong so cac l¢nh sau la hop l~ (a) char a == '\u0061 ':

(b) char '\u006!' == • a ':

(c)long phone = 8235469L;

Chuong iff. cec thanh phon co so cue Java

65

(d) float pi = 3.14159;

(e) double p = 314.l5ge-2;

3.3. Nhirng khai baa nao cua ham maint) sau day la dung (a) static void main(String arg[]){ /* ... */ 1

(b) public static int maint String arg[]) (/* ... */ 1

(c) public static void main(String arg[]){ /* */)

(d) public static void main(String[] argj ] /* */ I

(c) final static public void main(String[] arg)( /* ... */ \

3.4. Chuong trinh sau c6 16i hay kh6ng, neu c6 loi thi hay sira cho dung. //NhietDo

PUBLIC CLASS nhietDo{

public VOID main(String arg) { double fahre = 62.5;

double celsius = f2c{fahre); System.out.println(fahre + 'F = ' + celsius + 'c') i

}

double f2c(float f) {

Return (f - 32) * 5 /9;

}

}

3.5. Chuong trinh sau khi dich va chay se cho cai gi? public class MyClass{

public static void main(String[] arg) { String a, b, C;

c = new String ("Chu9t" ) ;
a = new String ( "Mea" J ;
b = a;
a = \~Ch6" i c = b; system.out.println(c) ;

}

3.6. Dieu gi se xay ra khi dich va chay chuong trinh sau: public class Progl{

public static void main(String[] argJ {

5.LTH-A

66

lQp trinh huong doi tuc;mg voi Java

int k = 1;

int i = ++k + k++ + +k; System.out.println{i) ;

}

3.7. Di~u gi se xay ra khi djcli va chay chuong trinh sau: public class prog2{

public static void main(String[) arg) { int k = 0;

int [) a = { 3, 6};

a [k] = k = 9; II Luu Y mire uu lien cua II cao han phcp grin = System.out.println(i + " " + a[O) + " " + a[l]);

} }

3.8. Cho biet kct qua thuc hien cua chuong trinh sau: public class prog3{

public static void main(String[) arg) { int k = 0, i = 0;

boolean r, t = true; r={t&O«i+=l));

r = {t && 0 < (i += 2));

r = (t I 0 < (k += 1));

r = (t I I 0 < (k += 2)); System.out.println(i + " " + k);

} }

3.9. Ket qua dich va chay chuong t.rinh sau la gi? public class Prog4{

public static void main(String[] arg) { int a = 0, b = 0;

int[] bArr = new int[l]; bArr [0] = bi inCl(a); inC2(bArr);

system.out.println{"a =" + a + " b = " + b + "

bArr = " + bArr[O));

public static void inCl(int xl { x++;};

5.LTH·B

Chuang 11/, Cae thanh phon co so cue Java

67

public static void inC2{int[] xl { X[OJ++i};

3.10. Vi@t chuong trmh nhap vao mot so nguyen va in ra dang nhi phan cua so do.

3.11. Vi@t chuong trinh nhap vao ngay, thang, nam va in ra ngay thu bao nhieu d6 trong narn (365 hoac 366 ngay doi voi nam n huan).

3.12. Vi@t chuong trinh nhap vao mot so nguyen va in ra tilt ca cac so nguyen to nho hen hoac bang so' nguyen d6.

3.13. Viet chuong trinh nhap vao mot so nguyen n va in ra tat ca cac so hoan thien nho hon hoac bang so n d6.

CHUONGIV

'" ... '" ... ~? '"

LOPVACACTHANHPHANCUALOP

cAc B6I WONG

.

4.1. D!NH NGHiA LOP

Dinh nghia mot lop la d;tic ta mot ki~u du: lieu mdi va rna ta each cai dat ki@u du lieu do, N6 c6 cu phap duoc qui dinh nhu sau:

l <Pham vi hoac kiem soat tru y n hap> 1 class <Ten lap>

[extends <Ten lap cha>l [implements <Ten giao dien»]

<Cac thanh phan cua lap>

trong d6 class I extends I implements la cac tit khoa. Nhirng phan trong cap [ va ] la tuy chon. Nhung phan nay se dUQC de cap chi tiet 0 cac phan sau.

<Cac thanh phan cua ldp> baa g6m cac bien, cac phuong thuc (ham) thanh phan va cac toan tii tao l(ip (constructor). Khai bao cac bien thanh phan nhu cia thao luan 0 muc 3.3. Cac ham va toan tu: tao lap se dUQC de cap 0 muc 4.2, 4.5 tiep thea. Than cua mot lop lai co th~ chua cac khai bao cua cac lop, giao dien (interface) khac va xem chung nhu la cac thanh phan cua lop.

4.2. f>iNH NGHiA HAM THANH PHAN

Hanh vi cua cac d6i tuong cua mot ldp ducc xac dinh bdi cac ham thanh phan cua ldp d6. CU phap d@ dinh nghia cac ham e6 dang t6ng quat:

I<Ph~m vi hoac thuoc tinh kj~m soat truy nh~p>l<Ki~u td lai> <Ten ham >( [<Danh sach tham bien hinh thircc-j) [<M¢nh de throws>! <N9i dung ella ham>

70

LQp trinh huong doi tugng vOi Java

<Ki~u tra lai> co th~ ia kieu nguyen thuy, ki~u lap boac kh6ng co gia tri Ira lai (kieu void).

-cDanh sach tham bien hlnh thirc> baa g6m day cac tham bien (ki~u vii ten) phan each voi nhau b&i dau phay,

Vi dy. 4.1. II T¢p Demo.java public class Demo {

public static void main{String args[]) {

if (args . length ::::::: 0) return; I/Ham kieu void co th~ sir dung return; output(checkValue(args.length)) i

}

static void output (int value) (II Ham kitu void kh6ng can sir dung return System.out.println(value);

static int checkValue (int i) { II Ham khac kieu void phai sir dung return d~ tra

if (i > 3) return 1 i II lai gia tri.

else return 2;

}

}

4.2.1. N~P CHONG cAc HAM THANH PHAN

Moi ham d~u c6 phan dinh danh ham, baa g6m ten cua ham, ki~u td. lai gia tI1 va danh sach cac tham bien. Trang lap trinh huang dOl tuong cho phep 8tl dung cling mot ten ham nhung dinh nghia nhieu noi dung thuc hien khac nhau. Nhirng ham nhu the dUQC goi la ham nap chong hay ham tai b9i (overloading).

Luu j: Co che nap chong cho phep mot ham c6 cling mot ten goi nhung da nh sach tham bien khac nhau, do vay 8e c6 cac dinh danh khac nhau. Nhirng ham rluQc nap chong vdi cac dinh danh khac nhau c6 cac phan cai dat thuc hien nhtmg cong viec khac nhau va c6 ki~u tra lai khac nhau.

JDK API da xay dung rit nhieu ham duoc nap chong. Vi du, ldp java.lang.Math c6 ham nap chdng minO xac dinh gia tri cue ti@u cua 2 so:

public static double min (double a, double b)
public static float min (float a, float b)
public static int min(int a, int b)
public static long min (long a, long b) Cling can luu y la danh sach tham bien cua cac ham nap chong phai khac nhau ve so luong hoac ve thu tv cac ki~u cua cac tham bien. Vi du:

Chuang IV. Lop va ccc thanh phon cuo lop ccc dOi tUQng

71

public void methodA(int a, double b) {/* ... */} public int methodA(int a) {return a;}

public int methodA() (return 1)

public long methodA(double a,int b) {return a*4} public long methodA(int a, double b) {return ~}

Cac ham tren c6 cac dirih danh tuong ling li't: methodA(int, double)

methodA (int)

methodA ()

methodA (double , int)

methodA(int, double)

/I (I) /I (2) II (3) II (4)

II No OK (5)

II (I ') II (2 ') II (3') 11(4')

II (5') gi6ng her nhu (I')

Bon nl)i dung cai dat dau cua ham methodA la duoc nap chong chinh xac vi danh sach cac tham bien khac nhau. Dinh nghia cho ham methodA(int, double) da c6 a (1) va sau d6 lai bi lap lai d (5) do vay phan cai dat cuoi cung nay kh6ng cho phep. Moi dinh danh ham chi c6 mot noi dung thuc hien duoc cai dat. Luc dich, nhung noi dung cai dat chinh xac se duoc giin cho dinh danh ham nap chong tuong ling d~ lien ke't thuc hien cac 10-1 goi ham.

Ngoai co che' nap chong cho cac ham con c6 co che viet de (overriding) cung clin phai duc,lc pha n biet.

4.2.2. VIET flE cAc HAM THANH PHAN vA VAN DE CHE BONG cAc BIEN

Trang nhieu truong hQP, mot ldp can co th~ viet de, thay d6i noi dung thuc hien cua nhung ham duoc thira ke til ldp chao Khi nhung ham nay duoc goi d@ thuc hien d6i vdi nhung d6i tuong cua lop can thi nl)i dung duoc dinh righ'ia mdi b ldp con se duoc thuc thi. Sau day la mot sO' chu y khi sli. dung co che viet de.

y' Dinh nghia mci cua ham viet de phai co cung dinh danh (ten goi va danh sach tharn bien) va cung ki&u tra lai gia trio

./ Dinh nghla moi cua ham viet de trong lop can chi c6 th~ xac dinh tat ca hO$C tap con cac ldp ngoai IG duoc k@ ra trong menh de cho qua ngoai l~ (throws clause - se trinh bay d chuong 5) .

./ Dinh nghia cua nhung ham se viet de kh6ng duoc khai bao final a lop chao

Vi du 4.2. Viet de va nap chong cac ham thanh phan

II Khachl-lang.java

import java.io.*;

72

LQp trinh huang doi tUQng vai Java

class Den {

protected String loaiHoaDon = "Hoa don nho: H; Vel)

protected double docHoaDon(int giaDien}

throws Exception { Y(2)

double soGio = 10.0,

hoaDonNho = giaDien* soGio; System.out.println(loaiHoaDon + hoaDonNho};

return hoaDonNhoi

}

}

class DenTuyp extends Den {

public String loaiHoaDon = "Hoa don lon:"; public double docHoaDon (int giaDien)

throws Exception {

double soGio = 100.0,

hoaDonLon = giaDien* soGio; System.out.println(loaiHoaDon + hoaDonLon) i return hoaDonLoni

/I Hj ehe bong (3)

1/ Viet de ham (4)

}

public double docHoaDon () { System.out.println{"Khong 'co hoa don!"); return 0.0;

public class KhachHang {

public static void main(String args[]) throws Exception {

DenTuyp denl = new DenTuyp(); Den den2 = denl;

Den den3 = new Den() i // G9i cac ham d1i viet de denl.docHoaDon(lOOO) ; den2.docHoaDon(IOOO) ; den3.docHoaDon(IOOO);

/I Truy nhap toi de bien thanh phan da bi viet de (b! che bong) System.out.println(denl.loaiHoaDon) i

// (6) // (7) /1 (8) II (9)

/1 (10) /1 (11) /1 (12)

// (13)

Chuang IV, Lop va coc thanh phon cue lop ccc doi tUC,1ng

73

System.out.println{den2.1oaiHoaDon) i System.out.println(den3.1oaiHoaDon) i II Goi cac ham nap chong

denl.docHoaDon() i

II (14) //(15)

}

Ket qua thuc hien cua chuong trinh KhaehHang:

H6a don IOn: 100000.00 H6a don IOn: 100000.00 Hoa don nho: 10000.00 H6a ddn IOn:

H6a don nho:

H6a don nho:

Kh6ng e6 H6a don'

Ham docHoaDon{) cua ldp eha Den duoc dinh nghia d (2) va sau d6 duoc viet de trong ldp can DenTuyp d (4). Nhung ham nay se bo qua ngoai l~ Exception (lop thu vien d g6i java.io."). Pharn vi ldp cua docHoaDon() e6 th~ thay dBi, vi du, chuyen tu protected sang public, va tham bien cung c6 thf khai bao final, vi du final int giaDien. Ldi goi ham docHoaDonO thuc hien d6i vdi d6i tuong cua ldp can DenTuyp va lop eha Den d (10) va (11) tUdng ling, ket qua thuc hien nQi dung da viet de d (4). Loi goi ham docHoaDonO d6i vdi d6i tuong cua lOp cha (lop Den) d (12) tat nh ien se thuc hien nQi dung dude dinh nghta d (2).

Luu j: Cac ham final, static kh6ng duoc phep viet de.

ce che che bong cua cac bien

V~ nguyen tiic, mot ldp con kh6ng duoc phep viet de cac bien thanh phan cua lop cha, nhung c6 th@ hi che khuat chung tuong tu nhu bien cue b(l trong lop con. Lop eon c6 th6 dinh nghia lai (che) cac bien da duoc dinh nghia trong lop chao Khi d6 cac bien nay cua lop cha se kh6ng th@ truy nhap true tiep thea ten d lop con. Trong ham cua lop con co th~ s-u: dung toan t-u: super'() (se de cap d muc 4.5) d~ truy nhap Wi cac bien cua lop cha b1 che khuat.

Trang vi du 4.2, bien loaiHoaDon duoc dinh nghia lai d ldp con DenTuyp (3), do vay vdi lenh (13) thi denl.loaiHoaDon se eho ket qua da dinh nghra lai d (3). Nhung 2 d6i tucng den2, den3 Iai thuoc lop cha Den do d6 va.n giu nguyen loaiHoaDon cua ldp cha duoc dinh nghta d (1).

74

19P trinh huong d6i tu(';mg voi Java

Viet de va nap chong la khac nhau

'I'ruoc tien can pha n biet ro hai co che viet de va nap chong la khac nhau trong Java .

.( Viet de yeu cau cung dinh danh ham (cung ten goi, cung danh sach tham s6) va cung ki6u tra lai ket qua da duoc dinh nghia tai lop chao

.( !'J,,:tP chong yeu cau khat nhau ve din h danh, nhung giong nhau vEi ten g9i ella ham, vi the chung sc khac nhau ve srllliQng, kieu, hay thu tv ella cac tham bien .

.( Ham c6 th6 nap chong d trong cung lop hoac d cac lop con chau .

.( Tu nhirng lOp con khi muon goi tdi cac ham d lop cha rna bi viet de t.hi phai goi qua toan tl:i dai dien cho lop cha, d6 la superi). D6i voi ham nap chong thi Iai khong can nhu the. Lei gQi ham nap chong dli<jC xac dinh thong qua danh sach cac ct6i so" hien thi"Ji sanh voi doi so hirih thuc d& xac dinh noi dung tuong ling .

...".." __ 4i' _') "" __ (#I

4.3. PH~M VI VA CAC THUQC TINH KIEM SOAT TRUY NH~P CAC

, ~.., (#I

THANH PHAN CUA LOP

Trong lap trinh huong d(;i tuong, khai niem ldp duoc su dung cti1 bao g6i va che gili'u th6ng tin. Tuy nhien giira cac d6i tlt(.1ng phai thuong xuyen trao d6i thong d iep voi nhau d~ thuc thi nhung yeu cau cua he thong. V$.y van de d;~t ra 18. cac thanh phan cua 16p duoc qUElD ly nhu the nao? Sau day cluing ta xet nhirng luat quan ly truy

nnap tdi cac thanh phan (bien, ham) cua ldp trong Java. .

4.3.1. PH~M VI COA cAc THANH PHAN

Pharn vi cua die thanh phan c6 hai loai:

• Pham vi lop cu a cac thanh phan,

• Pharn vi kh6i cua cac bien cue b9 (local) .

1 / Pham vi zap

Pham vi ldp xac dinh nhung thanh phan duoc truy nhap ben trong cua mot ldp (k@ ca. lop duoc ke tnua). Quyen truy nhap cua chiing thuong duoc xac dinn thong qua cac boO ngii (modifier): public, protected, private.

Ben trong dirih nghia cua ldp, cac bie'n tham chieu trti chfnh lop d6 va duoc quyen truy nhap tdi Uit ell cac tnanh phan cua n6 rna kh6ng can quan tam toi cac bel ngu cua chung.

Vi du 4.3. Pham vi lop cua cac thanh phan class BongDen{

Chuang IV. Lop va coc thanh phon cue lap ccc d6i IUQng

75

liCk bien thanh phfin

private int soWatts i II SO watts cua bong den

private boolean batTat; Jltruc - bong sang, false - tat

private string vi Tr i i II Noi d(11 bong den

II Cac ham thanh phan

public void batDen () {batTat :: true i } II Bar den

public void tatDen() {onOff = f a l.s e r ] IIT{ltden

public boolean tatHaySang() {return batTat;}

public BongDen nhanDoi(BongDen bongCu) { BongDen bongMoi = new BongDen(); bongMoi.soWatts = bongCu.sDWatts; bongMoi.batTat = bongCu.batTat; bongMoi.viTri = new string (bongCu.viTri) ;

/1 ( 1 )

II (2) II (3) II (4)

}

}

Ham nhanDoi() a (1) cua lop BongDen co tham bien bongCu va bien C\lC b9 bongMoi d@u tham chieu toi ldp BongDen. M$.c du cac bien thanh phan sOWatts. batTat . viTri la private (sa huu rieng) nhung chung vftn cho phep truy nhap d6i vdi ca 2 tham chieu tren a (2), (3), va (4).

21 Pham vi khot

Trang chuong trinh, cac lenh khai bao va cac lenh tnuc hien co th6 g9P lai thanh tung khoi (block) b§.ng each srt dung {, }. Chu y la than cua ham, cua lop ciing la mOt khoi. Cac khoi c6 th€ long nhau va khi do luat pham vi duoc ap durig cho cac bien cue b9. Lu/it pham. vi phat bi~u t6'ng quat la mot bier: dU(JC hhai btio d trong mot khot c6 pham vi xric dinh ben trong kh6i va kh6ng xac dinh. d ben ngoai kh{/i au.

Luu y;

-/ Trang cung mot pham vi kh6ng th@ khai baa mot bien hai IAn. Cac tham bien cung kh6ng th~ khai baa lai trong than cua ham. Luu y 1:1 trong cac khoi thi lenh khai baa la tt;( do, thu tv kh6ng quan trong, muon khai baa a chf> nao cung duoc mien la phai khai bao truoc khi stt dung.

-/ Pharn vi khoi cua bien duoc xac dinh k~ tu chE> biit dAu khai bao cho den ket thuc kho'i (gi;ip diu ngoac '}' tl1dng ling).

-/ C6 th~ co nhieu khoi long nhau nhung kh6ng dude dt nhau va nhirng bien khai baa d kh6i ngoai deu co pham vi xac djnh d trong moi khoi bao ben trong no.

76

lQp trinh huong d6i tu<;sng vOi Java

Vi (11,1: hi nh 4.1 minh hoa cac tfnh chat ve pham vi cua cac khci,

public static void main(String args[]) { /I Kh6i I

II String args = ""; khong the' khai bao lai cac tharn bien (I) char chuSo;

for (int k = 0; k < 10; ++k) { II Kh6i 2

switch(chuSo) { II Kh6i 3 case' I': int i; II (2)

default: int i: II (3) L6i VI khai baa lai i trong cung khoi )11 switch

if (true) { II Kh6i 4 in! i; II (4) OK

in! chuSo;l1 (5) L6i VI chuSo d5 diroc khai bao 6 kh6i ngoai, kh6i I

in! k;

II (6) L6i VI k d5 diroc khai baa i:J kh6i ngoai , khoi 2

int k;

II (6) OK

4.3.2.

Hinh 4, l . Minh hoa pham vi cua cae khO"i chuang trinh.

.. ....,. .... ~,. .....,......,..,...."f

CAC THUQC TINH KIEM SOAT TRUY NH~P CAC THANH PHAN CUA

LOP

Mot trong nhirng uu ditim cua phuong phap huang doi tucng la c6 thti t6 chuc du lieu thea nguyen 15' baa g6i va che giau th6ng tin. Cac thuoc tmh va ham tha nh phan cua lop c6 th@ khai baa them mfrt so b6 ngu d@ kiern soat quyen truy nhap doi vdi nhirng thanh phan d6. Khi thiet ke cac thanh phan cua ldp doi tuong, chung ta c6 th~ S-lI dung nhung b6 ngu sau:

• public

• protected

• mac dinh (kh6ng S-lI dung them b6 ngii khi dinh nghia lop)

• private

• static

• final

Chuang IV. Lop va coc thonh phOn cue lap ccc doi IUQng

77

• abstract
• synchro nize d
• native
• transient
• volatile Trang phan thao luan sau day chung ta sl1 dung mot so ky hieu cua UML (Unified Modeling Language) d~ minh hoa. UML ky hieu '+' eho thuoc tfnh public, '#' eho protected va -: , cho private.

(i) Cdc thanh. pluin. public

Thuoc tinh public xac dinh tinh cong khai ella cac thanh phdn, Thanh pha n khai baa corig khai (public) eho phep truy nhap moi noi trong h~ thong, d d6i vdi cac ldp cung g6i (package) Ian nhirng lop d cac g6i khac cung nhin th£ly duoc,

Vi d u 4.4. Tinh cong khai (public) cua cac thanh phan II Tep: Superclass/vjava

package goiAi

(1 )

II Dinh nghia g6i co ten goiA

public class SuperclassA{ public int superclassVarAi

public void superclassMethodA{) { 1* ... */}

/ I (2) II (3)

}

class SubclassA extends Supercla~nA{

void subclas sMethodA () {s".1--erclas sVarA = 20 i } 1/ (4)

class AnyClassA{

SuperclassA obj = new SuperclassA(); void anyClassMethodA() { obj.superclassMethodA() ;

/ / (5)

}

II Tep: Subclassft.java package goiB;

import goiA. * ; II Nh:1p cac lop dii duoc dinh nghia a goi co t00 gaiA. public class SubclassB extends SuperclassA{

void subclassMethodB() {superclassMethodA();}

(6)

II (7)

}

class AnyClassB{

78

LQp trinh huang d6i tUQng voi Java

superclasSA obj = new su~ rclassA(); void anyClassMethodB(){

obj .superclassVarA = 10;

II (8)

Vi d \1 4.4 e6 hui t~ p nguon gbm hai g6i cac lop duoc dinh ng hia a (1) va (6). Cac lap trong goi gaiB co th@' ,',1't dung (truy nhap hay nhin thay duoc) cac thanh phan public cua cac lop trong goi gaiA. Lop SuperclaseA 0 gaiA c6 2 lop can (ma roug hay ke thua): mot b Subclaeu/v trong RaiA va SubclassB t.rong gaiB. Khl nang truy nhap tdi cac thanh phrin public cua cue ldp trong 2 g6i t.reu ducc minh hoa d hlnh 4.2.

• Khachl: Tit lop can trong c1111g g6i e6 th5 truy nhap toi bien superclasss/ar A cua lop cha (4), vi cac bien khai bao cong khai cua ldp cha duoc ke thira sang cho cac ldp con ella no:

• Klwch2: Tu nhung ldp kh6ng kif thira cua lop SuperclassA, n hung trong cung g6i thi v5.n e6 th@ truy nhap duoc tdi thanh phan cong khai «uperclaseMethod.At) nhu a (5):

• Khach3: Ttl lop call kh6ng trong cung g6i van c6 th@ truy nha p tdi ham superclass Method.Ai) (7), vi cac ham khai baa cong khai ella ldp cha ducc ke thua sang cho cac lop can ella no;

• Khaeh4: Ttl nhirng lop khong ke thira eila lop Su.perclassA va d khac g6i thi van c6 th§ truy nhap duoc Wi thanh phan cong khai superclassVarA nhu a (8).

goiA

~ . "import"

I

----------~-- __ ------J-------------------,

goiB

+SupcrclasxVar A:int

Supcrclas-A ,'1.

~------------------~~

Khach3

Khach4

Subc1assR

AnyClassB

ob j: Su pcrcl assA

r-------------------~~

Khach2

obj: Su pccCl assA

Subc I asslvlct hmlA

+SllperclassMclhodA ~

I Kh'''hll ~ ~ __ J

,- L_ __ ~

AnyClassA

SubclusaA

anyclasslvlcthod A

SubClassMethodR anyCiassMcthodB

<

<J-- Quan h~ ke: thira

l ltnh 4.2. Kiln nang truy nhap dOl WJi cac thanh. pluin public.

Chuang IV, LOp va ccc thanh phon cue lop cdc d6i tUC,1ng

79

T6m lai die thanh phan khai puhlic: co mien xac dinh rong nhat, eo th~ nhin lhAy a moi noi Irong he thong.

(ii) Cac thanli phiin. protected

Nhirng thanh ph an duoc hao vi:; protectedcho phep truy nhap doi vdi tat d. cac lop trong g6i chua Wp do va t.ilt ca cac lop con (c6 th@ d nhung goi k hac) cua 16p chua chung. N6i each k hac. nhung lop kh6ng phai 18. lop can va d nhung g6i kh ac thi kh6ng duoc phep truy nhap toi cac thanh phan khai bao protected.

Vi dl;l 4.5. Thuoc tmh protected cua cac thanh phan

II Tep: Supcrclass Ajava package goiA;

publ ic c I ;'iSS Sllpen:L·l.<:;sA{

p ro t..oc t.ori .i III Sli pe rc I rlSS V c.l 0\ :

(I)

II Dinh nghiu goi co ten goiA

II (2)

pro t.cc.t.cd void e:;upc,classMelhod!\() {/"', ,*/) 11(3)

}

class Su be li:lssA PX Lend s Su pc rc 1 ossA {

vo i rl subchlss\lc:t:hmJ/\ () {SUpCTC 1 assVatf'l

20, }

II (4)

)

c I rlSS AnyC 1 i.lssA {

Supere LLssA ob_] = new SUpC.TC 1 ossA () vo tel rlnyC lae:;sMe t-.hod!\ () {

ob_] ,supel-cL'lssMcthodA () ,

II (5)

}

IIT¢p: SubclassB.java (6) package goiB,

iIllPOf"l. gaiA. '" :

II Nh~p cac lap da diroc dinh nghia 6' goi co ten gaiA.

public class SubclossB ex Lends SupcrrlassA{ Supe,cla~sA objA = new SubclassB(); SubclassB ob.) B = new SubclassB ()

void suhrlassMethodB(){

obj B. supp,classMl2t_hodf\ () : obJA,supcrclassMcLhodA()

II (7) II (8)

1/ Dung (9) II Sai (10)

}

}

80

L(lp trinh huang doi tuc;sng vai Java

class AnyClassB{

SuperclassA obj = new SuperclassA(); void anyClassMethodB() {

obj .superclassVarA = 10;

//Kh6ng cho phcp (II)

}

Kha nang nhin thfry dude cua cae thanh phan protected ella cac lop d hai g6i tren duoc minh hoa trong hinh 4.3.

l . "1"

~ DDPQr _

I

goiA

goiB

Khach3

Khach4

SuperclassA A

~----------------~I~ /_

SubclassB

AnyClass

#SuperclassVarA: int

obj: Superclass A

#SuperclassMcthodAO ~V SubclassMethodB anyClassMcthodB

I o ~Yf--+- f,\ -+--------------',

Khach2 Khach I _ ~

AnyClassA SubclassA <}----- Quan h¢ k€ thua
obj: Superc1assA < DU'Q'c phep

anyClassMethod Su be lassMet hodA 4-
Cam truy nhap
HiHiI 4.3. Khti nang truy nluip cua cdc thdnh phdn protected.

Phan tich hoat dong cua chuang trinh tren, chung ta nhan thay:

• Khachl: Tit lop can trong cung g6i c6 th~ truy nhap toi bien superclassVarA (4), vi cac bien khai baa protected cua lop cha duoc ke thua sang cho cac lop can cua n6;

• Khach2: Tu lop kh6ng ke thua cua ldp SuperclassA, nhung trong cung goi thi v&n c6 th~ truy nhap duoc tdi thanh phan protected superclassMethodAO nhu d (5);

• Khach3: Tu ldp can kh6ng trong cung g6i van c6 thJ truy nhap tdi ham superdassMethodAO (9), vi cac ham khai baa protected cua ldp cha duoc ke'thita sang eho cac lop can cua n6; nhung mQt d61 tuong tham chieu obJA cua SubclassB duoc tao ra thea SuperclassA sc kh6ng th~ nhin thay dude thanh phan duoc bao

_ Chuong IV. lOp va ceo thanh phon cue lop cae d6i tuc;mg

81

v~ ella ldp eha 2r goi khac (10). Dieu han che nay dam baa d.ng nhung ldp eon nam d nhtrng goi khac vdi g6i ella lop eha ehi eo th@ truy nhap duoc tdi nhung thanh phfin protected til ldp eha thong qua S\1 tham gia cua chung trong cau true phan eAp thea quan h~ ke thira.

• Khach4: Til ldp khong ke thua cua ldp SuperclassA va d khac goi thi kh6ng th@ truy nhap duoc toi thanh phan protected superclassVarA nhu d (11).

(iii) Cdc th.anh. pluiti private

Nhung thanh phan sd huu rieng private dude baa v~ chi.\t che nhat, kb6ng cha phep ke thira va chi cho phep truy nhap doi vdi nhimg d6i tuong trang cung lop. N6i each khac, nhtrng lop khac du la d cung mot g6i, hoac la die lop can cnau cimg khong duoc phep truy nhap true tiep tdi cac thanh phan rieng private.

Vi du d.B, Thuoc tinh private cua cac thanh phan II Tep: SupercJassA.java

package goiA i II Dinh nghia g6i co ten goiA public class SuperclassA{

private int superclassVarAi private void superclassMethodA(){ superclassvarA = IOi}

(1)

II (2)

II (3)

}

class SubclassA extends SuperclassA{ void subclassMethodA(){ superclassVarA = 20i}

II Kh6ng duoc phep (4)

}

class AnyClassA{

SuperclassA obj = new SuperclassA() i void anyClassMethodA(){ obj.superclassMethodA() ;

II Kh6ng diroc phep (5)

}

/1 T¢p: SubclassB.java package goiBi

import go i A. * ill Nhap cac lap da duoc dinh nghia (1 g6i co ten gaiA. public class SubclassB extends SuperclassA{

SuperclassA objA = new SubclassB () ; II (7)

SubclassB objB = new SubclassB () ; II (8)

(6)

6.lTH·A

lQp trinh hUCsng do' tuc;mg vOi Java

82

void subclassMethodB() {

obj B . s uperc 1 as sMethodA () i II Kh6ng diroc phcp (9)

obj A . s uperc las sMe thodA () i II Khong cho phep (' 0)

} }

class AnyClassB{

SuperclassA obj = new SuperclassA() i void anyClassMethodB() { obj.superclassVarA = 10i

1/ Kh6ng cho phcp (II)

} }

Kha nang truy nhap tdi cac thanh phan private cua cac lop d hai g6i tren duoc minh hoa trong hinh 4.4.

goiA ~-------- "import" -------- gaiB I
Khach3 Khaeh4
SuperclassA A SubclassB Anyclassfs
: V
SupcrclassVarA: int obj: Superc1assA
<, 1\
SuperelassMethodAO ~ Su bclassAMethodBO an yClass McthodBO
I- ~\ V I
1\
Khaeh2 Khaehl
AnyClass A Quan h¢ ke thira
SubclassA
obj: SuperClassA < Dl1Q'c phep truy nhap

anyClassMethodA() Su be lassMethodAO 4 Cam truy nhap
Hit/II 4.4. Khd nang tTUy nh~p clla cac thanh' phiin private.

Nhu nhan thay d tren, chi trong cling ldp duoc pnep truy nhap (nhin tnay) cac thanh phan private cua ffiQt lop, eon cac lop knac kh6ng th~ nhin thay duoc.

(io) Cdc thanh. phtin truu: dinh.

Nnung thanh phan mac dinh (default, kh6ng khai bao thuoc tinh public, protected, private) ella mot lop chi cho phep truy nhap d6i vdi nhirng lop trong cling g6i chua

6.LTH-B

Chuang IV. Lop va coo thanh phon cue lap cec d6i tllQng

83

ldp d6, k& ea. cac Idp con cua n6. N6i each khac, nhirng lop d nhung g6i khac thi khong duoc phep truy rihap toi cac thanh phan mac dinh, ng hia la cac than h phan mac dinh cling kh6ng dU9C phep kef thira. Nhu vay, cac thanh phan mac dinh se c6 pham vi nhin thay duoc rong bon cac thanh ph fin private, nhung hep han cac thanh pha n protected.

Luu j: Khi kh6ng stt du ng lcnh dinh nghia g6i package tenGoi;

nhu trong cac vi du 4.2, 4.3, 4.4, 4.5 thi tat ca cac lop duoc dinh nghla trong cung mot tep chuang trinh s6 duoc xern nhu IS. g6i mac dinh.

Vi dy. 4.7. 'I'huoc tinh mac dinh ella cac thanh phan II Tep: SupcrclasaAjava

package goiA; II Dinh nghia g6i co ten goiA

public class SuperclassA{

int superclassVarAi

void superclassMethodA() {/* ... */}

(1 )

II (2) II (3)

}

class SubclassA extends SuperclassA{

void subclassMethodA ( ) {superclas sVarA ::: 20 i} II (4)

}

class AnyClassA{

SuperclassA obj ::: new SuperclassA() i void anyClassMethodA() {

obj .superclassMethodA() i

}

II (5)

}

II T¢p: Subc1assB.java package goiB;

import goiA. * ; II Nhap cac lap dii dmrc dinh nghia a g6i co ten goiA.

public class SubclassB extends SuperclassA{

void subclassMethodB() {

(6)

objA.superclassMethodA() i

}

II Kh6ng cho phep

(7)

}

class AnyClassB{

SuperclassA obj ::: new SuperclassA() i void anyClassMethodB(){

84

l¢p trinh huang d6i tU<;Ing vol Java

obj.superclassVarA = 10;

II Kh6ng cho phep

(8)

} }

Minh hoa cho kha nang truy nhap tdi cac thann phan mac dinh cua cac ldp a hai g6i trong vi du 4.5 la hinh 4.5.

"import"

~------------------------------.

goiB I

goiA

Khach3

Khach4

obj: Superclass A

SubclassB

AnyclassB

SuperclassA It1.

r-------------~:_V

SuperclassVarA: in! ~"""'--I\f----+--I

s;u7classMeth'f(\) ~,--_--+-+S_U_b_c_la_s_s~~< .... e_th_o_d_B_() __ la_n_Jy~laSsMethodBO Khachll

r-------~---~

Khach2

SubclassA

AnyClassA

<J---- Quan he k€ thira

obj: SuperCIassA

~ Diroc phep troy nnap

anyClassMethodAO SubclassMethodAO

'"----------' +

Cam troy nhap

Hinn 4.5. Khd nang truy nh(ip eua ctic thanh' phti"n mac dinh,

Tom lai bon thuoc tinh tren duoc S11 dung d@ xac dinh kha nang truy nhap doi vdi cac thanh phan cua lop d6i tuong.

ThuQc !fnh Cac thanh phan
public Cho pnep truy nhap Cl rnoi noi, du'c)c phep ke thua.
protected Cho phep truy nhap doi voi cac lap trong cling g6i va nhling
lop con (rnd r¢ng) d cac g6i knac. £lu'<;1C phep ke thCta.
M~c dlnh (kh6ng khai bao Chi cho phep truy nh~p doi voi cac lop trang cunq g6i, k€! ca
them bo nglt) cac lop con. Kh6ng cho phep ke thira.
private Chi cho phep truy nhap Cl tronq cling \Op.Kh6ng cho phep ke
thira. Ngoai cac thudc tmh xac dinh pham vi thea lop nhu tren con c6 mot s6 thuoc tinh (bel ngu) rna ta cac di;\.c tmh cua cac ldp, ham, bien thanh phan.

Chuang IV. Lap va cac thanh phon cue lop ceo d6i IllQng

85

(u) Cdc thanli phan static

Khi khai bao cac thanh phan cua lop c6 tinh chat tinh, nghra la nhimg thanh phan d6 la chung cho ca. ldp chu kh6ng phai la thanh phan cua ca th~ nao ca thi Slt dung tir kh6a static dung truce phan khai bao. Nhu vay cac thanh phan static se la chung cho tat ca cac d6i tuong trong mot ldp, con nhung thanh phan kh6ng static thi thudng moi bien deu c6 ban sao cac gia tri rieng cua tung d6i tuong.

Vi dl;l4.8. Minh hoa ve quan 15' truy nhap cac thanh phan tinh static /1 NhaKho.java

class BongDen{

/I Cac bien thanh phan

int soWatts;

boolean onOff; String viTrii

II Thanh phan tinh

static int demBongi II Dinh nghia roan ttt tao lap BongDen() {

soWatts = 45;

onOff = true;

II SCI watts cua bong den II true - bong sang, false - tat II Noi d~t bong den

II Dem s6 bong cua ca nha kho (I)

II D*t mac dinh bong moi voi cong suat 4S watts II Khi lap bong moi thi b~t luon

viTri = new String("XYZH); ++demBong;

1/ Tang demBong len mot khi hip moi (2)

II Ham thanh phdn tinh static public static ghiBong(){ System.out.println //systern.o~t.println

("So bong den eua nha kho: "+ demBong);/1 (3) (''Cong suat cua bong den: "+ soWatts); II (4)

}

public class NhaKho{

public static void main(String args[]){

BongDen. ghiBong () ; /I GQi ham tinh theo ten lap (5)

BongDen den! = new BongDen () i II Tao ra bong moi

Sys tern. out. pr int In ("Gia tri eua bo dem: .. + BongDen.demBong); /1 (6) BongDen den2 = new BongDen () i II Tao ra bong moi

den2 . ghiBong () i II GQi ham tinh theo ten d6i nrong (7)

86

lQp Irinh huang doi tu(;mg vai Java

System.out.println

("Gia tri cua bo dem: " + den2.demBong); 1/ (8)

}

Ket qua thuc hien cua chuong trinh:

So bong den cua nhakho: 0 Gia tri eua bo dem: 1

So bong den eua nha kho: 2 Gia tri eua bo dem: 2

LUll y:

./ Cac bien du li~u ttnh cua lop nhu bien demBong khai baa a (1) se duoc tl,i khoi tao gia trj (0 eho bien ki~u int) khi lop duoc nap vao chuong trinh d@ thuc hien va cac gia trj cua chung la si'i dung chung cho ca ldp, Vi the bien tlnh demBong khong duoc khoi tao tuong minh nhung dU:QC mac dinh vi vay l~nh tang gia tri len 1 nhu a (2) la thuc hien duoc .

./ Truy nhap tdi cac thuQc tinh du lieu tinh c6 th~ thuc hien theo hai each: + Thong qua ten lop nhu a (5), (6),

+ Th6ng qua ten doi tuong nhu a (7), (8);

./ Cac ham thanh phan tinh (vi du ham ghiBong() a (3» chi duoc phep truy nhap toi cac thanh phan tmh khac, vi du demBong; khong duoc phep truy nhap toi nhung thanh phan khong khai bao static, vi du soWatts a (4).

(vii) Cdc thanli pluin. final

Bien thanh phan final duoc xem nhu la hAng, gia tri cua no se khong th~ thay deli duoc ngay sau khi dB. duoc khdi tao.

Nhu a chirong 3 chung ta da biet, Java co hai 10~i ki@u: nguyen thuy va tham chieu,

• Doi vdi cac bien final ki~u nguyen thuy, khi chung duoc khdi tao gia tri thi se khong thay deli duoc,

• DOl vdi cac bien final ki~u tham chieu (reference), gia tri tham chien (la dOl tucng) se kh6ng thay d6i duoc, nhung cac thanh phan (trang thai) cua d6i tuong co th@ thay d6i dt1QC.

Ngoai ra d.n luu y:

./ Cac bien final kh6ng can khdi tao gia tri khi khai baa va con dude goi la bien "trang". Song phai gan gia trj truce khi sl'.t dung. Bie'n static kh6ng can khoi tao gia tri triroc khi sit dung rna no khdi tao gia tri mac dinh .

./ Cac ham khai bao final d trong ldp la day du (co du nl_)i dung can thuc hien) va

Chuang IV. Lop va ccc thanh phon cue lop ccc d6i hJQng

87

khong th~ viet de d cac lop can cua lOp d6, nghia la khong thay d6'i duoc .

..; Cac bien final static duoc slt. dung chung trong chuong trinh nhu cac hang (constant) tuong tu nhu tu kh6a const cua ng6n ngu C. Thong thuong ten cua bien hAng duoc viet hoa va gan gia tri ngay khi khai baa nnu d (1) trong vi du 1.9 .

..; Deli voi cac thanh phi'in final, chuong trinh dicn e6 th~ thuc hien duoc t(;i uu h6a trong viec sinh rna .

..; Ldp ciing co the" khai bao final. Lop finalla kh6ng md rQng duoc. N6i each khac, hanh vi (cac ham thanh phan) cua lop final 13. knong thay d6i duoc d cac ldp con cua n6. Nhu vay c6 th6 xcm lop [inal ii: loai lop "day du" con lop abstract (se de cap d phan sau) la k nong di'iy duo Hien nhien mot lop kh6ng th~ vira 18. final vua 18. abstract .

..; Thu vien cua -Iava API e6 nhieu lop final da duoc xay dung, vi du java. lang. String la loai lOp kh6ng th~ tao ra nhung ldp di;ic biet la can chau cua n6 duoc.

Vi d1;l4.9. Minh hoa kha nang truy nhap cua cac tnanh phan final cua lop II NhaKho.java

class BongDen{

II Bien thanh phan final static (1)

final static double KWH GIA = 500. oo;/IGiu ban dien 5UOd/KWH int soWatts;

1/ Ham thanh phan final

final public void datWatt(int watt) {

soWatts= watt; II (2)

public void datLaiGia() {

KWH GIA = 400. 00; II Sai VI khong cho phep thay d6i lai bien final static (3)

} }

class DenTuyp extends BongDen{

II Khong the nap chong lai cac bam cua BongDen

pub lie va i d da t Wa t t (int w) {II Thir viet de ham final do v~y chtrong trtnh

soWat ts = 2 * w; II dich se kh6ng thirc nien - Sai (4)

} }

public class NhaKho{

88

LQp trinh huang doi tuc;Jng vai Java

public static void main{string args[]) {

final BongDen den = new BongDen() i (5)

den. sowat ts =100;, II Dtroc phep thay d6i trang thai d6i tirong (6)

den= new BongDen () ,. I/Sai VI khong cho phep thay d6i d6i tirong (7)

} }

public static double KWH_CIA duoc dinh nghia a (1) nhu la hdng trong chuong trinh Java va do vay sau d6 kh6ng th~ thay dfi'i (3). Ham final datWatt() d (2) khong cho phep nap chong, viet de nhu a (4). Tucng tv nhu vay, doi tuong tham chieu final den duoc dinh nghia a (5) thi sau do kh6ng thay dfi'i tham chieu duoc (7), nhung duoc phep thay deli trang thai cua doi tucng do (thay dfi'i thanh phan),

(viii) Cdc ham thanh. phiin. abstract

Ham thanh phan khai bao triru tuong (abstract) co dang:

abstract <Ki~u tra lai> <Ten ham>([<Danh sach tham bien>l)r<M~nh de throws»]:

Ham abstract la ham prototype, chi khai bao phan dinh danh ham rna kh6ng dinh nghia nQi dung thuc hien, do v~y n6 la ham kh6ng dAy duo Ham abstract thudng chi tel chuc cho cac ldp abstract va n6 phai duoc cai d~t nQi dung thuc hien d trong cac lop con chau cua lop chua ham d6.

Luu y:

./ Ham final kh6ng th@ khai bao abstract va nguoc lai, ./ Cac ham trong interface d~u la cac ham abstract.

(ix) Cac ldp abstract

Lop duoc khai baa abstract la ldp truu tucng khong c6 th~ hien. Cau true nay thuong duoc stl dung d~ nham thuc hien telng quat h6a nhimg khai niern, nhirng thuc th~ C\1 th& trong thuc teo Vi du, chung ta c6 th& stl dung ldp Vehicle (phuong tien giao thong) nhu In lop triru tudng va lam lop cd sa d& tu d6 rna rQng thanh nhung lop Cl,1 th€ (kh6ng truu tuong) Car (0 t6), Bus (6 t6 bus), V.v.

Lop abstract phai mot ham abstract. Nhung ham nay sau d6 se dude cai dat nQi dung thuc hien trong cac lop con chau cua lop chua cluing.

Vi d\l4.10. Minh hoa kha nang truy nhap cua lop abstract / /NhaKho . java

abstract class BongDen{ II Cac bien thanh phan

int sowatts; 4

(1)

Chuang IV. Lop va cec thanh phon cue lop cec dol tUQng

89

boolean batTat; String viTrij

II Ham thanh phan

public void batSang() {batTat = truei } public void tat() {batTat = false; } public boolean sangTat() {return batTati } /I Ham abstract

abstract public double xacDinhGia () ; II Khong cai d:~t n¢i dung

}

class DenTuyp extends BongDen{ II Bien thanh phan

int dODai;

int mau;

/I Cai di).t ham abstract xacDinhGiaO public double xacDinhGia() { return 500.00;

}

}

class NhaKho{

public static void main(String args[]) { DenTuyP denI = new DenTuyp();

II (5)

system.out.println("Gia dien: U + denl.xacDinhGia());

BongDen den2 i II Diroc phep khai bao kieu abstract (6)

BongDen den3 = new BongDen () j IISai v116p abstract kh6ng c6 the hien

}

(x) Cdc ham thanh. ph/in. dang b9 synchronized

Java ho tr<;l chuong trinh thuc hien da luting (multi threads). C6 th~ c6 nhieu luong muon thuc hien d6ng thci tren m9t d6i tuong nao d6. C6 nhung loai thie't bi, vi du nhu may in, kenh truyen chang han, doi hoi phai e6 co che' d~ chi mot luong duoc thuc hien, nghia 13 phai thuc hien dbng b9. Tai moi thoi diim, chi mot luong (tien trinh) duoc khai bao d6ng bQ synchronized duoc thuc hien tren d6i tucng chi dinh.

Vi d\l4.11. Minh hoa hoat d{)ng cua cac ham synchronized class Stack{

private Object[] stackArraYi private int topfOfStackj

90

L¢p trinh huang dol tu~ng vai Java

synchronized public void push(Object elem) { /1 (1) stackArray[++topOfStack] = elem;

}

synchronized public Object pop() { Object obj = stackArray[topOfStack]; stackArray[topOfStack] = null; return obj;

/ I (2)

1/ Nhirng ham khac

public Object peek() { return stackArray[topOfStack] ;

}

Hai ham push() va pop() trong lop Stack 1a dong b9 synchronized. Do vay khi c6 nhieu luang muon dfiy cac phan tti' vao Stack (ham push()) hay muon lily ra cac phan ttt (ham pop(» thi chi mot luong duoc phep thuc hien, con nhirng luang khac se phai cho,

(xi) Cac ham thanli phan native

Ham khai bao native duoc goi 1ft ham ngoai. N9i dung thuc hien cua ham native kh6ng duoc dinn nghia trong Java rna dinh nghia 0 nhirng ngon ngu lap trinh khac nhu C/C++. Nhiing ham native chi cAn khai baa prototype nhu la cac thanh phan cua ldp.

JNI (Java Native Interface) la mot loai API (Abstract Programming Interface) cho phep cac ham cua Java goi tdi ham ngoai duoc cai dat trong C.

Vi d\l4.12. Minh hoa hoat d9ng cua cac ham native class Native{

/ * Kh6i static nay dam baa thu vien cac ham native duoc nap xu6ng tnroc khi chung duoc goi,

*1 static {

Sys tern. loadLibr ary ( "Nat i veMethodLib") i 1/ Nap thu vien

}

nati ve void nati veMethod (); 1/ Ham prototype native /1 ...

}

class Khach{

Chuang IV. LOp va coc thanh phon cue lop ccc doi tU(;lng

91

public static void main(String[] args){ Native aNative = new Native(); aNative.nativeMethod() ;

}

(xii) Cdc bien. thanh. phiin. transient

Cac d6i tuong c6 th~ luu tru twin tv va viec tim kiern chung se trb nen don gian va nhanh khi cac trang thai cua chung la nhat quan, cef dinh,

C6 nhung truong hQP, gia trj tham chieu cua d6i tuong trong lop la kh6ng nhat quan (hay thay d6i) khi dOl tuong duoc luu trft. Nhirng bien cua cac d6i tuong nhu the' c6 th~ khai baa voi thuoc tinh transient d~ chi ra rang gia tri cua n6 se kh6ng duoc luu tru khi defi tuong cua lop d6 duoc tao ra tuan tv trong bQ nhd.

Trang vi du sau, bien nhietDo cua lop ThiNghiem duoc khai baa transient d (1) bdi vi n6 la yeu t6thay d6i nhieu nhat khi lam thi nghiem d nhung ngay tiep theo. Bie'n khoiLuong khai baa d (2) lai binh thirrrng, it thay deli. Khi t6 chuc luu tru cac ket qua ThiNghiem mot each tuan tv trong bQ nhd thi gia tri nhietDo se kh6ng duoc ghi lai rna chi ghi lai cac gia trj khoiLuong.

class ThiNghiem implements Serializable{

/ / .,.

trans ient int nhietDo j II Gia tri hay thay deli

double khoiLuong;

II Gia tri c6 dinh

}

Luu j: Thuoc tinh transient khong th~ Slt dung cung voi bien static.

(xiii) Cdc thanli pluin. volatile

Trang qua trinh thuc hien, m¢t sefluong co th~ thuc hien che giau nhung gia tri cua cac bien thanh phan vi nhieu ly do khac nhau. Bdi vi m¢t s61uong c6 th@ cung chia se mot bien va khi d6 cac thao tac d9C, ghi du lieu cho cac bien chung do c6 th@ dAn tdi ket qua khong nhat quan. Gia tti cua nhung bien nhu the' co th~ thay d6i rna khong luong truce duoc. Java Slt dung b5 ngtr volatile d& khai baa cho nhung bien c6 th@ thay d5i bat thucng va thong bao cho chudng trinh dich khong nen thuc hien toi uu doi voi nhirng bien nhu the'.

Vi du trong lop DieuKhien dudi day, bien docGio ella dong ho co th~ khai baa volatile vi gia tIi cua n6 c6 th6 thay d5i trong qua trtnh 4ieu khi~n ella mot luang

92

lQp trinh huang doi tUQng vai Jovo

dang thuc thi cong viec rna cac lu6ng khac kh6ng bie't duoc va dam bao lu6n doc duoc gia tri hien thoi cua dong ho.

class DieuKhien{

/l ...

volatile long docGioi

112 Ian doc lien tiep se cho ket qua khac nhau

}

Tom lai, cac til kh6a rn6 ta cac d:)e tinh cac thanh phan duoc phep slt dung eho lOp, ham thanh phan, bien thanh phan va bien cue b9 d~ xac dinh pharn vi nhin thay cua chung trong h~ thong. Chung ta t6ng ke't lai trong bang sau.

ro khoii

Lap

Ham thanh phan

Bien thanh phan

Bien eye bC>

abstract

static

public

protected

private

final

synchronized

native

transient

volatile

Trang do dau ,,,,, ngh'ia la duoc phep S11 dung con diu '_' Ia kh6ng duoc phep S11 dung.

.. A J .. ..

4.4. CAC DOl SO CUA CHUONG TRINH

Giang nhu chucng trinh eua' C/C++, chung ta co th~ truyen cac tharn so eho chuong trinh tren dong lenh, vi du:

java Colors red green blue

Chucng trinh java th6ng dich lop Colors d~ xac dinh so cac chii cai trong cac doi so' red, green, blue Chuong trinh Colors e6 th~ vie't nhu sau:

Vi dV4.13. Truyen tharn so eho chuong trinh II Colors.java

Chuang IV. Lop va coc thanh phOn cue lop e6e dOi tUQng

93

class Colors{

public static void main(String args[J) { for lint i = Oi i < args.lengthi i++)

System. out. println("D6i s6: " + (i+l) + II (" + args [iJ ) + ") co " + args [iJ . length () + "ky til") ;

}

}

Khi thuc hien chuong trinh cho ke't qua:

D6i s6: 1 (red) c6 3 ky tt;( D6i so': 2 (green) co 5 ky tu D6i s6: 3 (blue) c6 4 ky tv

~., _.J

4.5. TOAN TU T~O L~P COl TUQNG

Muc dich chinh cua toan t-li tao lap (constructor) la dJ:it cac gia tri khoi tao cho cac d6i tirong khi mot d6i tuong duoc tao ra bang toan t-li new.

'I'oan tli tao l$.p co dang khai bao nhtt sau:

{<ThuQc tmh>] <Ten lop> ([ <danh sach tharn bie'n>]) { II NQi dung can tao l~p

}

Toan tli tao lap gi6ng nhu cac ham thanh phan va chi khac d phan dilu cua dinh nghia. Phan [<ThuQC tfnh»] <Ten lop> gom nhimg thong tin sau:

./ <Thuoc tinh> chi co th& su dung: public, protected, private hoac mac djnh nhu da

trinh bay d philn tren .

./ <Ten lop> luon trung vdi ton cua lop chua toan tti d6. Mi}t s6'luu j d6l oai cac totin. tu t{LO l4p:

./ Khong sir dung cac b6 ngu khac voi toan nr tao lap,

./ Toan ur tao lap la loai ham dac biet khong c6 kie;u tra lai, ngay cii. kieu void ciing khong dLTQ'c sir dung,

./ Toan t1i tao lap chi s-li dung dude vdi toan tu new.

4.5.1. loAN III T~O L~P MAC D!NH

Toan tll: tao lap mac dinh (default) lit toan til' tao l$.p khong c6 tham bien. <Ten lop> 0 {/* ... ""1}

94

LQp trinh huang dOi tuc;mg vai Java

Khi mot l{jp kh6ng djnh nghia mot toan til tao lap nao c:i thi h~ thong se t-I,i dong cung dip toan ttl tao lap mac dinh kh6ng tuong minh. Toan til tao l~p mac dinh kh6ng tuong mi nh tuong during vdi dang:

<Ten ldp> 0 { } II Kh6ng lam gi ca

Vi du duoi day trong lOp BongDen kh6ng djnh nghia toa n tv tao lap va khi tao l$-p doi tuong thi sv dung toan ttt tao lap kh6ng Wong minh,

class BongDen{

1/ Bien thanh phan int soWattsi

boolean batTati

String viTrii

II Khong dinh nghia toan ti'r tao l~p /1 ...

}

class NhaKho{

public static void main(String args[]) {

BongDen denl = new BongDen (l ill GQi toan tv tao l~p mac dinh

(l)

II ...

}

Toan tv tao l~p mac dinh kh6ng tuong minh duoc cung ca'p:

BongDenO {}

Nnu dinh ngh'ia d tren, no chang lam gi ca. Tuy nhien, khi 8il dung vdi toan til new d@ tao ra d6i tuong thi cac bien ki6u nguyen thuy nhu soWatts, batTat, ui'I'ri se duoc khoi tao cac gia tri mac dinh tu'dng ling la 0, false, null.

Chung ta cung co th@ dinh nghla toan til tao l$.p mac dinh tuong minh. Vi du

class BongDen{ 1/ Bien thanh phfin (1)

int soWattsi boolean batTati String viTrii

II Dinh nghia toan nr tao l~p mac dinh BongDen(){

Chuong IV. lOp va ccc thanh phon cue lop ccc doi tuc;mg

95

soWatts = 40; batTat = true;

viTri = new String("XXH);

}

II ...

class NhaKho{

public static void main(string args[]) {

BongDen den1 = new BongDenO;/1 G9i toan IU 1,.10 lap mac dinh nrong minh

II ... }

}

Luu. j: Khi trong mot lop da dinh nghia m9t hay nhieu toan ttl tao l~p thi h~ thong 56 kh6ng cung dip toan ttl tao Iap mac dinh kh6ng tudng minh. Do d6 khi muon sli dung toan ttl tao lap mac dinh thi phai dinh nghia tuong minh toan ttl d6. Vi du:

class BongDen{

II Bien thanh phan

( 1)

int soWatts; boolean batTat; String viTri;

II Dinh nghia roan til tao lap khong mac dinh BongDen(int w, boolean s, String v) { soWatts = W;

batTat = s;

viTri = new String(v} i

II ... }

class NhaKho{

public static void main(String args[]) {

BongDen d1 =new BongDen (); II Sill vi loan tir tao l~p mac dinh khong drn;x:: dinh nghia BongDen d2 = new BongDen(lOO, true, "Nha bepH}; II OK II ...

}

}

96

LQp trinh huang d6i tUQng vai Java

4.5.2. N";P CHONG loAN III 1";0 LAp

Giong nhu cac ham thanh phan, cac toan tit tao lap c6 th& nap chong (tdi bQi . overloaded) vdi nhieu nQi dung thuc hien khac nhau. Vi du, trong kip BongDen thi toan tV: tao l~p BongDenO c6 dinh nghla mac dinh tuong minh (1), va nap chong d€ khdi tao d6i tuong vdi cac gia tri xac dinh khac. Vi du,

class BongDen{

II Bien thann phan

(1)

int sOWattsi boolean batTati string viTrii

II Dinh nghia toan tii tao l~p mac dinh

BongDen() { soWatts· = 40 i batTat = truei

viTri = new String("XX") i

}

II Dinh nghia toan tii tao l~p khong mac dinh

BongDen(int w, boolean 5, String v) { soWatts = Wi

batTat = Si

viTri = new String(v)i

II ... }

class NhaKho{

public static void main (string args[]l {

BongDen dl=new BongDen() i aOK

BongDen d2 = new BongDen (100 I true, "Nha bep") i II OK

II ...

}

Chuang IV. Lop va cec thonh phon cue lop cec d6i tw;mg

97

4.5.3. su HoAN THANH CUA £)01 TVQNG

MQt s6 d6i tu{jng co th~ g:ln vdi nh img tai nguyen (nhu tQP, ket noi m ang) va chung doi hoi phai giai phong tuong minh. Co che hoan thanh cua dOl tuong cung cip mot ke sach ct~ mot dai tuong co th~ thuc hien mot hanh dong bat ky truce khi b9 nhd bi giai ph6ng. BQ don rae tu dQng (Automatic Garbage Collector) goi ham [inalizet) da dune xay dung trong ldp Object c6 dang:

protected void finalizet) throws Throwable d~ tap hop rae 19-i (bo vao thung rae) truce khi tieu huy chung.

Ham nay e6 th~ duoc viet de d lop con d@ thuc hien nhung cong vice thich hop truoc khi huy bo d6i tuong.

Vi du 4.14. Stl dung bQ finalizer

II T¢p: Finalizer.java

class Dien{

static int dem; static int congChung; protected int Ian; public Dien() {

Ian = dem++; ++congChung;

II (1)

protected void finalize() throws Throwable ( H~)

super.finalize() ;

--congChung;

class TrinhDien extends Dien { H(3)

int[] fat;

public TrinhDien (int n l { II (4)

fat = new int[nj; System.out.println(lan + ". Hello");

protected void finalize() throws Throwable { H(m System.out.println{lan + ": Bye"); super.finalize() ;

98

lQp trinh huang dol tuc;mg vai Java

}

}

public class Finalizer {

public static void main(String args[]) { n(m int soLan, thoiGian;

try {

soLan == Integer. par s e In t (arg s (01);// Ddt doi so 1 thanh int thoiGian == Integer.parseInt (args [1] ); }catch(IndexOutOfBoundsException e) { System.err.println("Usage: Finalizer <soLan> <:thoiGian>") i returni

}

for (int i == 0; i <: sot.an , i++) { /1 (7)

new TrinhDien(thoiGian) ;

}

System. out .println (Dien. congChung+ \\; tieptuc") i 1/ (8)

}

Sau khi dich va thuc hi~n l~nh Java Finalizer 5 500000

Se cho ket qua

0: Hello 1: Hello 1: Bye 2: Hello 2: By.e 3: Hello 3: Bye 4: Hello

1: tiep tue

'Vi du tren minh hoa each s11 dung [uializet), Cnuong trinh tao ra mot s6 d6i tuong (soLan) vci kich thuoc (thoiGian) duoc dua VaG dudi dang d6i so cua chuong trinh. Chu trinh d (7) trong ham maini) tao ra dOl tuong cua lop TrinhDien, nhung kh6ng duoc luu tru d~ truy nhap tiep. Viec tao ra m{lt doi tuong cua TrinhDien duoc thuc

7.LTH·8

Chuong IV. Lop va cec thanh phon eua lop ccc d6i tuc;Jng

99

hien boi toan ti1 tao lap (4), xin cip phat mang cac so nguyen cho fat. M6i llin tao ra doi tuong cua TrinhDien a (4) lai in ra man hinh s6Ian va ": Hello". Ham [inalizei) 0 (5) duoc goi truce khi doi tuong duoc dua vao thung rae, M6i ltin thuc hi~n n6 in ra 86 lan, ": Bye" va sau d6 goi ham finalizeO cua lop Dien a (2). Ke't qua cua chuong trinh cho thay mot d6i tuong chua duoc don va n6 con tiep tuc hoat dong trong h~ thong. Luu y ke't qua in ra man hinh (s6d6i tuong tao ra va duoc don) phu thuoc nhieu VaG tham s6 thu hai, thoiGian cang IOn thi hftu nhu chi co mot do'i tuong chua dude don, thoiGian nho nhu khoang nho hen 9000 thi ca 5 d6i tuong se vjin tiep tuc hoat dQng.

-- ".,... - ., ,

4.6. QUAN H~ KE THUA GllfA CAC LOP

MQt trong cac co che cd cd dJ si't dung lai duoc cac doan chuong trinh trong lap trinh huong d6i tuong la co che' kc tnua. Tit mot lop duoc xay dung t6t, chung ta co th~ dan xuat ra nhieu lop moi, nhieu kiE)u moi (duoc goi la lop can, lop din xuat, hay ldp kc thira). Lop co so con duoc gQi Ia lop cha, lOp cha me. Lop can c6 th~ duoc b6 sung them mot 86 thuoc tinh va ham d~ xac dinh them cac tinh chit, hanh vi cua nhimg doi tuong cu th~ hon hoac co th~ thay d6i cac ham thanh phan duoc ke thua (public, protected, mac dinh nhu trinh bay a muc 4.3) tu lop chao

Java chi h6 tro ke' thiia don. (tuyen tinh), nghia Ia mt;t lap chi he'thila duac til mot ldp chao Do v$_y giira cac ldp co quan h~ ke trnra vdi nhau co th~ t6 chuc thanh cau true phan cap e6 thu: bac. Trang Java lop cd sa nhat, lam cd sa (goc cua cau true phan ca"p) cho tilt ca cac ldp ke thua la lop Object.

Chung ta nhac lai la moi lap cua Java de'u to. lap con chtiu miic dinh. cua Object.

Vi du, cac lOp d vi du 4.8, 4.9, 4.10 cac lOp BongDen, DenTuyp, NhaKho co th@ rna ta quan h~ ke' thua thea ky phap cua UML nhu hinh 4.6.

BongDen

NhaKho

DenTuyp

Hinh 4.6. Quan h¢ ki'thila giiia cdc ltip.

100

LQp trinh huang d6i tUQng vdi Java

Cli phap qui dinh quan h~ ke thua trong Java la su mo rong cua ldp cha, c6 dang: <Ten lop can> extends <Ten ldp cha> {

II Cac thuoc tinh dir lieu bel sung

/1 Cac ham thanh phan bel sung hay viet de

Luu y:

.;' MQi doi tuong cua lop can cung se la d5i tuong thuoc lOp chao Do v~y viec gan mot d6i tuong cua lop con sang cho bien tham chieu doi tuong cua lop eha la sl,l' rnd rong ki~u va do d6 khong din ep ki~u .

.;' NgU:Qc lai gan mot doi tudng cua lOp eha cho bien tham chieu doi tuong thuoc lop

can se phai thuc hien ep ki~u. Luu y khi d6 se e6 thJ bt t6n that thong tin. Vi du,

class SuperClass {/* */}

class SubClass extends SuperClass {/* */}

class UserClass {

1/

publish static void maln (String args []) {

SuperClass superl = new SuperClas s (); II Ti.IO fa d6i tucng lop cha SuperClass super2 = (SubClass)" subl; 1/ Thu hep kieu nen phai ep kicu SubClass subl = superl; IIMarQngki€u

}

4.6.1. ToAN ru MOC XiCH GIOA cAc LOP KETHUA THIS() vA SUPERO

Cae toan til tQ-O lap kh6ng the'viet de a cdc lap dan xu/it (lap con). Chung co the'duqc nap ch6ng nhung pluii trong cung 1(Jp.

Trang Java e6 2 toan tii: tao l$,p d~e biet eo ten la thist) va super() duoc sii: dung d~ m6e xich giua cac lop e6 quan h~ ke thua vdi nhau.

T03n tii tao I~p thisO

Toan tii: tao If!.p nay duoc sii: dung dJ tao ra deli tuong cua lop hien thoi.

Vi du 4.15. Nap chong toan ttt: tao lap II T¢p: NhaKho.java

class BongDen{

II Bi€n thanh phan private int sowattsi

(I)

Chuang IV, Lop va cec thanh phon cuo lop ccc dOi tuc;sng

101

private boolean batTati private String viTrij

II Dinh nghia roan tit tao lap mac dinh, so 1 BongDen() {

soWatts = 40i batTat = truei

viTri = new String(~xxH); System. out. pr Lnt.LnrToan tit so I");

(2)

II Dinn nghia roan tit tao lap khong mac dinh, so 2 (3)

BongDen(int W, boolean s) {

soWatts = Wi

batTat = Sj

viTri = new String(nXXH) j System. out. println("Toan tu so 2");

II Dinh nghia toan nr tao J~lp kh6ng mac dinh, s6 3 n~p chong (4)

BongDen(int soWatts, boolean batTat, String viTri) { this.soWatts = soWattsi

this.batTat = batTat;

this.viTri = new String (viTri) ;

Sys t em. out. pr int In(,,Taan tit so 3");

II ... }

public class NhaKho{

public static void main(String args[]) {

BongDen dl=new BongDen () ; II OK

BongDen d2 = new BongDen (100 I true I "Nha bep" ) i II OK

BongDen d3 = new BongDen (100 I true) i II OK

II ...

}

Trang lop BongDen e6 3 toan ti1 tao lap dUQC nap chong d (1), (2) va (3). Tham chieu this cung duoc 811 dung trong ham maint) d (4) d@ xac dinh cac doi so tuong ling doi cua twin ttt tao lap.

102

lQp trinh huang doi tUQng vai Java

Vi du 4.16. Su dung toan tv this() // Tep: NhaKho.java

class BongDen{

// Bien thanh phan

private int sOWatts; private boolean batTati private String viTri;

/1 Dinh nghia toan tu tao lap mac dinh, so 1 BongDen() {

this (40, true) i

System. out. print In(''Tmin ttc so I");

(I)

(2)

II Djnh nghia roan Iii tao lap kh6ng mac dinh, so 2 BongDen(int w, boolean s) { this(w, S, "XX")i

System. out. print In(''Toan ttc so 2");

(3)

/I Djnh nghia toan tir tao lap kh6ng mac dinh, so 3 nap ch6ng BongDen(int soWatts, boolean batTat, String viTri) { this.soWatts == soWatts;

this.batTat == batTat;

this.viTri = new String(viTri)i

System. out. println("Toan tiI so 3");

}

(4)

public class NhaKho{

public static void main(String args[]) {

BongDen dl = new BongDen () ; II OK

BongDen d2 == new BongDen ( 100 I true, "Nha bep") ; II OK

BongDen d3 = new BongDen(lOO, true); /10K

II ...

}

}

Chuong trinh nay hoat dQng giong nhu chuong trinh d vi du 4.15, nhung khac la trong dinh nghia 2 toan ti't tao l~p d (1) va (2) co S11 dung cau ttl' thist) d~ gan cac d6i so tuong ling cho cac dOl tuong m6i khi tao l~p ra chung.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->