ng on ngu lap trinh java
TRANSCRIPT
-
8/10/2019 Ng on Ngu Lap Trinh Java
1/115
Ngn ng lp trnh Java
-
8/10/2019 Ng on Ngu Lap Trinh Java
2/115
TNG QUAN TI LIU Nhng khi nim trong lp trnh hng i tng. C bn v ngn ng Java.
C bn v i tng (Objects), nhng i tng dliu n gin. Lp (Classes) v k tha (Inheritance) Giao din (Interfaces) v Packages.
Gii quyt nhng li thng gp khi vit chngtrnh.
-
8/10/2019 Ng on Ngu Lap Trinh Java
3/115
Bi 1: Nhng khi nim trong lptrnh hng i tng
-
8/10/2019 Ng on Ngu Lap Trinh Java
4/115
i tng l g? nh ngha: i tng l mt gi phn mm bao
gm nhng bin (variables) v nhng phnngthc lin quan (related methods).
Variables: lu tr trng thi (states) ca i tng. Methods: th hin nhng hnh ng (behavior)
ca i tng.
Vic ng gi ny c 2 li ch: Tnh module (Modularity).
Che giu thng tin (Information-hiding).
-
8/10/2019 Ng on Ngu Lap Trinh Java
5/115
Thng ip (Message) l g? Nhng i tng phn mm tng tc v giao tip
vi nhau bng cch truyn thng ip (sendingmessage).
Thng ip c 2 li ch quan trng: Mi tng tc gia cc i tng u thc hin c
ch bng cc thng ip.
Nhng i tng c th khc process, trn mykhc u c th gi/nhn thng ip cho nhau.
-
8/10/2019 Ng on Ngu Lap Trinh Java
6/115
Lp (class) l g? Lp l mt m t v nhng bin, phng thc cho
tt c nhng i tng thuc lp .
S khc nhau gia i tng vi lp: i tng l mt th hin (instance) c th ca mt
lp. Thut ng i tng (object) nhiu khi c dng
ch c lp (class) v nhng th hin (instance) calp.
-
8/10/2019 Ng on Ngu Lap Trinh Java
7/115
K tha (Inheritance) l g? Lp trnh hng i tng a thm nhng nh
ngha: lp con (subclass), lp cha (superclass), ktha (inherit), override.
Lp con k tha ton b nhng bin ca lp cha.Ngoi ra, lp con cn k tha mt s phng thcca lp cha.
Li ch ca k tha: lp con cung cp nhng phngthc chuyn bit (code reuse). Lp trnh vin c thto ra nhng lp abstract nh ngha nhngphng thc chung.
-
8/10/2019 Ng on Ngu Lap Trinh Java
8/115
SUMMARY Class l khun mu cho nhng i tng. Objects c to ra t class. Th no l constructor. Khi to i tng nh th no. Bin v phng thc ca lp. Bin v phng thc ca instance. Interface l mt giao thc ca nhng hnh ng.
Implement mt interface l implement tt c nhng phngthc trong interface.
-
8/10/2019 Ng on Ngu Lap Trinh Java
9/115
Interface l g? Trong ngn ng lp trnh Java, interface l mt kiu.
Ging vi class, interface nh ngha cc phngthc. Khc vi class, interface khng implement ccphng thc ny.
Interface c li ch: Th hin phn chung ca nhng lp khng c quan h vi
nhau.
Khai bo nhng phng thc m lp phi implement. Phi by giao din ca i tng m khng phi by lp ca
i tng. Mt cch thc hin a k tha.
-
8/10/2019 Ng on Ngu Lap Trinh Java
10/115
Bi 2: C bn v ngn ng Java
-
8/10/2019 Ng on Ngu Lap Trinh Java
11/115
Bin (Variables)
-
8/10/2019 Ng on Ngu Lap Trinh Java
12/115
Variables Bin l mt mc d liu c t tn. Cch khai bo mt bin: type name [= ];
//integersbyte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;int largestInteger = Integer.MAX_VALUE;long largestLong = Long.MAX_VALUE;
//real numbersfloat largestFloat = Float.MAX_VALUE;double largestDouble = Double.MAX_VALUE;
//other primitive typeschar aChar = 'S';boolean aBoolean = true;
-
8/10/2019 Ng on Ngu Lap Trinh Java
13/115
Kiu d liu (1): PrimitivesKeyword Description Size/FormatIntegers
byte Byte-length integer 8-bit twos complement
short Short integer 16-bit twos complementint Integer 32-bit twos complement
long Long integer 64-bit twos complement
Real numbers
float Single-precision floating point 32-bit IEEE 754double Double-precision floating point 64-bit IEEE 754
Other types
char A single character 16-bit Unicode character
boolean A boolean value (true/false) true or false
-
8/10/2019 Ng on Ngu Lap Trinh Java
14/115
Kiu d liu (2): v dLiteral Value Kiu d liu178 int
8864L long
37.266 double
37.266D double
87.363F float
26.77e3 double
c chartrue boolean
false boolean
-
8/10/2019 Ng on Ngu Lap Trinh Java
15/115
Kiu d liu (3): tham chiu Arrays, classes, interfaces l kiu tham chiu (reference).
reference An object/arrayobjectName
-
8/10/2019 Ng on Ngu Lap Trinh Java
16/115
Tn bin Bt u l: k t, $, _. Theo sau l k t, s, $, _. Phn bit
ch hoa ch thng. Ngn ng Java yu cu: l mt nh danh hp l. Khng phi t
kha. Duy nht trong phm vi (scope) ca n. Quy c t tn: tn bin bt u l ch thng. Tn lp bt
u bng ch hoa. K t u mi t vit hoa. K t (_) thngch c dng ngn cch nhng t trong constants.
-
8/10/2019 Ng on Ngu Lap Trinh Java
17/115
Phm vi ca bin
-
8/10/2019 Ng on Ngu Lap Trinh Java
18/115
Khi to bin type variable = ;//integersbyte largestByte = Byte.MAX_VALUE;short largestShort = Short.MAX_VALUE;int largestInteger = Integer.MAX_VALUE;long largestLong = Long.MAX_VALUE;
//real numbersfloat largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
//other primitive typeschar aChar = 'S';boolean aBoolean = true;
-
8/10/2019 Ng on Ngu Lap Trinh Java
19/115
Bin final Ta c th khai bo bin trong bt k phm vi no l final. Gi tr
ca bin final khng th thay i c sau khi khi to. Khai bo: final type variable [= ]; V d:final int aFinalVar = 0;
final int blankFinal;
blankFinal = 0; Mi c gng thay i bin final sau khi khi to s pht sinh
li compile time.`
-
8/10/2019 Ng on Ngu Lap Trinh Java
20/115
Ton t (operators)
-
8/10/2019 Ng on Ngu Lap Trinh Java
21/115
Ton t tnh ton (Arithmetic)Operator S dng M t
+ op1 + op2 Cng; ni xu (String)
- op1op2 Tr
* op1 * op2 Nhn
/ op1 / op2 Chia
% op1 % op2 Php ly phn d ca op1 / op2
Ch vi php ton %: Dng cho c s thc. Quy tc: a % b = (du ca a) abs(a) % abs(b);V d: -5 % 3 = -2; -5 % -3 = -2; 5 % 3 = 2; 5 % -3 = 2
-
8/10/2019 Ng on Ngu Lap Trinh Java
22/115
Unary Arithmetic Operators
Operator S dng M t
+ +op Tr v kt qu int nu op kiu byte, short,char
- -op Tr v kt qu o du ca op
-
8/10/2019 Ng on Ngu Lap Trinh Java
23/115
Shortcut Arithmetic Operators
Operator S dng M t
++ op++ Tng op nn 1; tr v gi tr ca op trckhi tng
++ ++op Tng op nn 1; tr v gi tr ca op sau khitng
-- op-- Gim op i 1; tr v gi tr ca op trc khigim
-- --op Gim op i 1; tr v gi tr ca op sau khi
gim
V d 1: a = 5; b = a++ + ++a + a++; a = ?, b = ?;V d 2: a = 5; b = a-- + ++a + a++; a = ?, b = ?;V d 3: a = 2; array[a] = a = 0;
-
8/10/2019 Ng on Ngu Lap Trinh Java
24/115
Relational Operators
Operator S dng M t
> op1 > op2 Tr v true nu op1 ln hn op2
>= op1 >= op2 Tr v true nu op1 ln hn hoc bng op2
< op1 < op2 Tr v true nu op1 nh hn op2
=,
-
8/10/2019 Ng on Ngu Lap Trinh Java
25/115
Conditional Operators
Operator S dng M t
&& op1 && op2 Tr v true nu op1 v op2 true. Khng lnggi op2 nu op1 false
|| op1 || op2 Tr v true nu op1 hoc op2 true. Khnglng gi op2 nu op1 true
! !op Tr v true nu op false
& op1 & op2 Tr v true nu op1v op2 true. Lun lunlng gi op2. Thc hin bitwise AND vi 2
ton hng s.| op1 | op2 Tr v true nu op1 hoc op2 true. Lun lun
lng gi op2. Thc hin bitwise OR vi 2ton hng s.
^ op1 ^ op2 Tr v true nu op1 v op2 l khc nhau.
(XOR logic)
-
8/10/2019 Ng on Ngu Lap Trinh Java
26/115
Shift Operators
Operator S dng M t
op1 >> op2 Dch phi op1 op2 bits. Lp y bn bn tri
bng bit du (Signed right shift).>>> op1 >> op2 Dch phi op1 op2 bits. Lp y bn tri bng
0 (Unsigned right shift).
V d: 13 >> 1: 6; -13 >> 1: -6; -13 >>> 1: 2147483641;
V d: 1
-
8/10/2019 Ng on Ngu Lap Trinh Java
27/115
Bitwise Logic Operators
Operator S dng M t
& op1 & op2 AND bit. Ch p dng cho kiu integeral.
| op1 | op2 OR bit. Ch p dng cho kiu integeral.
^ op1 ^ op2 XOR bit. Ch p dng cho kiu integeral.
~ ~op Ly b bit (complement). (0->1, 1->0). Chp dng cho kiu integral.
-
8/10/2019 Ng on Ngu Lap Trinh Java
28/115
Assignment Operators
Operator S dng M t
= op1 = op2 Gn gi tr op2 cho op1. Tr v gi tr caop1 sau khi gn.
op= op1 op= op2 Vit tt ca op1 = op1 op op2. C mt lith: khng phi p kiu.opc th l: +, -, *, /, %, &, |, ^, ,>>>
Li th khng phi p kiu:
byte a = 2;
a = (byte)(a + 3);
Vit gn:a += 3;
-
8/10/2019 Ng on Ngu Lap Trinh Java
29/115
Others Operators
Operator S dng M t
?: op1 ? op2 :op3
Nu op1 true, tr v op2; ngc li tr vop3.
[] Dng choarray S dng khai bo, khi to, truy cp phn tmng.
. Dng cho itng
Truy cp variables, methods ca i tng,class.
(params) Dng trong
methods
Khai bo danh sch cc bin.
(type) (type)op p kiu
new To i tng To i tng/array mi.
instanceof op1 instanceofop2
Return true nu op1 l mt th hin ca op2.(op2 l class type, interface type, array type).
-
8/10/2019 Ng on Ngu Lap Trinh Java
30/115
Biu thc
-
8/10/2019 Ng on Ngu Lap Trinh Java
31/115
nh ngha Biu thc l mt chui cc bin, ton t, li gi phng thc
c to thnh theo ng c php ca ngn ng. Kt qu trv mt gi tr.
V d: aChar = S, The string + value,Character.isUpperCase(aChar). Trong Java th t lng gi cc ton hng trong biu thc l
duy nht: t tri -> phi. Sau php ton c thc hin datrn th t tnh ton ca ton t. V d:
1. int[] a = {4, 4}; 2. int b = 1; 3. a[b] = b = 0;Line 3 equivalent: a[1] = b = 0;
-
8/10/2019 Ng on Ngu Lap Trinh Java
32/115
Th t u tin ca ton tNhm Ton t
Unary ++ -- + - ! ~ (type)
Arithmetic * / %
+ -
Shift > >>>
Comparison < >= instanceof
== !=
Bitwise & ^ |
Short-circuit && ||
Condition ?:
Assignment = op=
-
8/10/2019 Ng on Ngu Lap Trinh Java
33/115
Cu lnh - statement
-
8/10/2019 Ng on Ngu Lap Trinh Java
34/115
nh ngha Cu lnh tng ng vi mt cu trong ngn ng t nhin.
Cu lnh to nn mt n v thc thi y . Nhng biu thc sau y c th to thnh cu lnh bng
cch b xung du (;) vo cui biu thc:1. Nhng biu thc gn: a = S;2. Biu thc s dng ++, --: a++;3. Nhng li gi phng thc: System.out.println(String);4. Biu thc to i tng: Integer obj = new Integer(4); Cu lnh khai bo: double aValue = 933.24; Cu lnh iu khin: for, if, while, do while, switch, return,
break, continue.
-
8/10/2019 Ng on Ngu Lap Trinh Java
35/115
Khi lnh (Blocks) nh ngha: l mt nhm cha 0 hoc nhiu lnh c t
trong cp {}. N c th c s dng bt k ni no m lnhn c th s dng.
V d:if(Character.isUpperCase(aChar)) {System.out.println(The upper character);System.exit(0);
}
-
8/10/2019 Ng on Ngu Lap Trinh Java
36/115
Cu lnh iu khin
-
8/10/2019 Ng on Ngu Lap Trinh Java
37/115
while, do - while
+ while () {
statement
}
Lp khi iu kin cn ng. Kim tra iu kin trc khi thc hinlnh.+ do {
statement
} while();
Lp khi iu kin cn ng. Kim tra iu kin sau khi thc hinlnh.? 1. while (i > 0) i--; 2. do i--; while (i > 0); 3. do i--; j--; while (i >
0);
-
8/10/2019 Ng on Ngu Lap Trinh Java
38/115
for
for (initialization; termination; increment) {
statement(s)
}
Lp v hn: for ( ; ; ) {}Ch : phn khi to (initialization) v phn bc nhy (increment)
c th cha nhiu biu thc (khai bo) ngn cch bi du (,).for (int i = 0, j = 1; i < 10; i++, j+=2) {}? for (int i = 0, long j = 1; i < 10; i++, j+=2) {}? for (int i = 0, long j = 1; ; i++, j+=2) {}
-
8/10/2019 Ng on Ngu Lap Trinh Java
39/115
Enhanced for
Java 1.5 cung cp lnh for m rng lp qua mng, collection(Iterable):
for (var : ) {}
V d:int[] a = {4, 3, 2, 1};
for(int i : a) { System.out.println(i); }
Collection col = new ArrayList();
Integer iobj;
for(iobj : col) { System.out.println(iobj); }
-
8/10/2019 Ng on Ngu Lap Trinh Java
40/115
if, if/else
Cu lnh if r nhnh da trn biu thc logic:if () { statement(s) }
Phn else c th c hoc khnng:
if () {statement(s)
}
else {
statement(s)}
?: if (aChar = A) { System.out.println(aChar); }C th dng ton t ? : thay th cu lnh if/else
-
8/10/2019 Ng on Ngu Lap Trinh Java
41/115
switch
Lnh r nhnh da trn biu thc dng int (byte, short, char, int;but not long) hoc kiu lit k enum(Java 1.5)
switch() {
case :
statement(s);
break;
case :
statement(s);
break;[default:
statement(s);
}
-
8/10/2019 Ng on Ngu Lap Trinh Java
42/115
Lnh x l exceptiontry catch finally
try {
statement(s)
} catch(exceptiontype name) {
statement(s)} finally {
statement(s)
}
C th c nhiu khi catch vi exeption type khc nhau. Khi finally lun c thc hin nu khi lnh try c thc
hin (tr khi ta dng lnh System.exit()).
-
8/10/2019 Ng on Ngu Lap Trinh Java
43/115
break, continue, return(branching statements)
break dng kt thc vng lp for, while, do while: break[label];
continue dng b qua vng lp hin ti: continue [label]; return thot khi phng thc v tr v gi tr (nu c): return
[];
loop1:
for(i = 0; i < 100; i++) {
for(j = 0; j < 1000; j++) {
if (j == i * 12 + 7)break loop1;
}
}
-
8/10/2019 Ng on Ngu Lap Trinh Java
44/115
Bi 3: C bn v i tng(Objects), nhng i tng d liun gin.
-
8/10/2019 Ng on Ngu Lap Trinh Java
45/115
Life Cycle ca mt i tng
-
8/10/2019 Ng on Ngu Lap Trinh Java
46/115
To ra i tngC 3 bc chnh: Khai bo bin tham chiu (reference): type name Khi to i tng: new class
Gi constructor ca i tng: constructor cng tn vi lp,khng c gi tr tr v.C th gp thnh mt bc:Point originOne = new Point(23, 94);
Ch : Khi nh ngha class, nu ta khng nh ngha bt kconstructor no, java compiler s to cho ta mt defaultconstructor khng c tham s, cng access modifier vi class.
-
8/10/2019 Ng on Ngu Lap Trinh Java
47/115
S dng i tng Tham chiu n bin ca i tng (qualified name):
objectReference.variableName
Gi phng thc ca i tng:objectReference.method([argumentList])
Access Modifier: private < default < protected < public:
+ private: this object, class only.
+ default: all classes in the same package.
+ protected: the subclasses. Java 1.5 c thm hn ch: nusubclass package khc, ch c th truy cp n protectedmembers ca i tng hin thi.
+ public: all classes.
-
8/10/2019 Ng on Ngu Lap Trinh Java
48/115
Thu hi nhng i tng khng cns dng
i tng khng cn c s dng khi cc tham chiu n nra khi phm vi hoc khng cn tham chiu n n:
Point pt = new Point(0, 0); pt = null;
Java t ng thu hi nhng i tng khng cn c s dnggarbage collection. Ta c th thc y garbage collection bng: System.gc() hoc
Runtime.gc().
Ta khng th khng nh c khi no mt i tng s b thu
hi.
-
8/10/2019 Ng on Ngu Lap Trinh Java
49/115
Character
-
8/10/2019 Ng on Ngu Lap Trinh Java
50/115
Static methods ca lp Character
Method Description
boolean isLetter(char ch)boolean isDigit(char ch)
Determines whether the specified char valueis a letter or a digit, respectively.
boolean isWhiteSpace(char ch)Determines whether the specified char value
is white space according to the Javaplatform.
boolean isUpperCase(char ch)boolean isLowerCase(char ch)
Determines whether the specified char valueis upper- or lowercase, respectively.
char toUpperCase(char ch)char toLowerCase(char ch)
Returns the upper- or lowercase form of thespecified char value.
toString(char ch)Returns a String object representing the
specified character value.
int digit(char ch, int radix)Returns the numeric value of the character in
the specified radix.
-
8/10/2019 Ng on Ngu Lap Trinh Java
51/115
String, StringBuffer, StringBuilder
-
8/10/2019 Ng on Ngu Lap Trinh Java
52/115
Khi no s dng String,StringBuilder, StringBuffer
String: Khi ni dung ca xu s khng thay i String objectl immutable (i tng s khng thay i sau khi khi to).
StringBuilder (Ch t Java 1.5 mi c lp ny): Khi ni dung ca
xu s thay i. Ch c 1 thread truy cp n ni dung ca xu(Not threadsafe). B li, tc nhanh. StringBuffer: Khi ni dung ca xu s thay i. C th c nhiu
thread truy cp n ni dung ca xu (threadsafe). Hn ch tc chm.
StringBuilder, StringBuffer nh ngha method append cho bt kkiu d liu no.
-
8/10/2019 Ng on Ngu Lap Trinh Java
53/115
To String, StringBuilder,StringBuffer
Hy tra cu trong JDK 1.5 nhng constructor ca cc lp ny.V d:String palindrome = "Dot saw I was Tod";
char[] helloArray = { 'h', 'e', 'l', 'l', 'o' };String helloString = new String(helloArray);
System.out.println(helloString);
Constructors ca StringBuilder (tng t vi StringBuffer):StringBuilder(), StringBuilder(CharSequence), StringBuilder(int),StringBuilder(String).
-
8/10/2019 Ng on Ngu Lap Trinh Java
54/115
di ca String, StringBuilder,StringBuffer
di: phng thc length(), tr v int l di ca xu tnhtheo s k t.
StringBuilder, StringBuffer cn c phng thc capacity(), tr v
int l ln ca b m.V d:String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
-
8/10/2019 Ng on Ngu Lap Trinh Java
55/115
Truy cp n cc k t trong String,StringBuilder, StringBuffer
Phng thc charAt(int), v substring(int [, int]).V d:String anotherPalindrome = "Niagara. O roar again!";
char aChar = anotherPalindrome.charAt(9);
-
8/10/2019 Ng on Ngu Lap Trinh Java
56/115
Tm kim k t, substring trongString
Method Description
int indexOf(int)int lastIndexOf(int)
Returns the index of the first (last) occurrence of thespecified character.
int indexOf(int, int)int lastIndexOf(int, int)
Returns the index of the first (last) occurrence of thespecified character, searching forward(backward) from the specified index.
int indexOf(String)int lastIndexOf(String)
Returns the index of the first (last) occurrence of thespecified string.
int indexOf(String, int)int lastIndexOf(String, int)
Returns the index of the first (last) occurrence of thespecified string, searching forward (backward)from the specified index.
booleancontains(CharSequence)
Returns true if the string contains the specifiedcharacter sequence
-
8/10/2019 Ng on Ngu Lap Trinh Java
57/115
Thay th k t, substring trongString
Method Description
String replace(char,char)
Replaces all occurrences of the character specified as thefirst argument with the character specified as the secondargument. If no replacements are necessary, the originalstring object is returned.
String replaceAll(Stringregex, Stringreplacement)
Replaces each substring of this string that matches thespecified regular expression.
-
8/10/2019 Ng on Ngu Lap Trinh Java
58/115
So snh Strings, tng phn trongString
Method Description
boolean endsWith(String)boolean startsWith(String)boolean startsWith(String, int)
int compareTo(String)int compareToIgnoreCase(String)
boolean equals(Object)boolean equalsIgnoreCase(String)boolean contentEquals(CharSequence)
boolean regionMatches(int, String, int,int)boolean regionMatches(boolean, int,String, int, int)
boolean matches(String regex)
-
8/10/2019 Ng on Ngu Lap Trinh Java
59/115
Thao tc trn String
Method Description
String concat(String)
String[] split(String, int)
String[] split(String)
int - max return array size
CharSequencesubSequence(int, int)
String trim()
String toLowerCase()String toUpperCase()
-
8/10/2019 Ng on Ngu Lap Trinh Java
60/115
Thao tc trn StringBuilder,StringBuffer
StringBuffer append(boolean)StringBuffer append(char)StringBuffer append(char[])
StringBuffer append(char[], int, int)StringBuffer append(double)StringBuffer append(float)StringBuffer append(int)StringBuffer append(long)StringBuffer append(Object)
StringBuffer append(String)
StringBuffer delete(int, int)StringBuffer deleteCharAt(int)
StringBuffer insert(int, boolean)StringBuffer insert(int, char)StringBuffer insert(int, char[])StringBuffer insert(int, char[], int,
int)StringBuffer insert(int, double)StringBuffer insert(int, float)StringBuffer insert(int, int)StringBuffer insert(int, long)StringBuffer insert(int, Object)StringBuffer insert(int, String)
StringBuffer replace(int, int, String)void setCharAt(int, char)
StringBuffer reverse()
-
8/10/2019 Ng on Ngu Lap Trinh Java
61/115
Number
-
8/10/2019 Ng on Ngu Lap Trinh Java
62/115
Number classes
-
8/10/2019 Ng on Ngu Lap Trinh Java
63/115
Nhng method chung ca lpNumber
Method Description
byte byteValue()short shortValue()
int intValue()long longValue()float floatValue()double doubleValue()
Convert the value of this number object to the primitivedata types of byte, short, int, long, float, and double.
compareTo
Compare this number object to the argument. Note thatthe Number class does notimplement the Comparable
interface, but most of the subtypes implementComparable.
boolean equals(Object)Determine whether this number object is equal to the
argument. Note that the Number class does notoverride the equals method from Object..
-
8/10/2019 Ng on Ngu Lap Trinh Java
64/115
Mt s constant hu ch ca lp Floatv Double
Constant Description
Float.NaNDouble.NaN
Not a Number. Returned by certain methods in
the java.lang.Math class when the result isundefined for the arguments passed to themethod.
Float.NEGATIVE_INFINITYDouble.NEGATIVE_INFINITY
The negative infinity value for a float or a double.
Float.POSITIVE_INFINITYDouble.POSITIVE_INFINITY
The positive infinity value for a float or a double.
-
8/10/2019 Ng on Ngu Lap Trinh Java
65/115
Chuyn t String sang Number
S dng phng thc static ca wrapper class (Byte, Integer,Double, Float, Long, Short): valueOfreturn wrapper type.
V d:
float f = Float.valueOf(9.3).floatValue();double d = Double.valueOf(9.3e2).doubleValue();
-
8/10/2019 Ng on Ngu Lap Trinh Java
66/115
Chuyn t Number sang String
C 3 cch:
Dng ton t gp xu vi xu . Dng phng thc static String.valueOf(primitive).
Dng phng thc static toString(primitive) ca cc lp: Byte,Short, Integer, Long, Float, Double.V d:int i;
String s1 = + i;String s2 = String.valueOf(i);
String s3 = Integer.toString(i);
-
8/10/2019 Ng on Ngu Lap Trinh Java
67/115
Nhng php ton s hc nng cao
Method of Mathclass
Description
double abs(double)float abs(float)
int abs(int)long abs(long)
Tr v gi tr tuyt i
double ceil(double) Tr v gi tr nguyn ln nht nh hn i s
double floor(double) Tr v gi tr nguyn nh nht ln hn i s
double rint(double)Tr v gi tr nguyn gn vi i s nht kiu
double (rintround integer)
long round(double)int round(float)
Tr v gi tr lm trn ca i s kiu long, int
-
8/10/2019 Ng on Ngu Lap Trinh Java
68/115
Arrays
-
8/10/2019 Ng on Ngu Lap Trinh Java
69/115
Tng qut v Array
Array l mt cu trc lu tr nhiu gi tr ca cng mt kiu. di ca array c thit lp khi array c to ra. Sau khito ra, di ca array khng thay i c.
-
8/10/2019 Ng on Ngu Lap Trinh Java
70/115
To v s dng Arrays (1)
Khai bo bin tham chiu n array: elementType[] name;int[] anArray; //Khng khai bo kch thc ca array.boolean[] anArrayOfBooleans;
Object[] anArrayOfObjects;String[] anArrayOfStrings;
To (cp pht) array: new elementType[size];anArray = new int[10];
Array Initializers: shortcut syntax to v thit lp gi tr choarray: {list of values};
boolean[] answers = {true, false, true, true, false};
-
8/10/2019 Ng on Ngu Lap Trinh Java
71/115
To v s dng Arrays (2)
Truy cp n phn t ca Array: arrayname[index]for(int i=0; i
-
8/10/2019 Ng on Ngu Lap Trinh Java
72/115
Array ca Objects
Array c th cha kiu tham chiu (reference) cng nh kiu cs (primitive). Vic to, khi to u ging nhau:
String[] anArray = {String One, String Two, String Three};
Object[] anObjArray = { String, new Integer(10), new Byte(2)};
-
8/10/2019 Ng on Ngu Lap Trinh Java
73/115
Array ca Arrays (1)
Array c th cha nhng phn t l Array. Khi , cp phtArray bng new, ch s cui cng khng c c mt.
String[][] anArray = { {One, Two}, {Three, Four}};
int[][] aMatrix = new int[4][]; aMatrix[1] = new int[3]; aMatrix[2]= new int[5];
-
8/10/2019 Ng on Ngu Lap Trinh Java
74/115
Copy Array
copy array, ta dng phng thc static ca lp System:public static void arraycopy(Object source, int srcIndex, Object
dest, int destIndex, int length).
-
8/10/2019 Ng on Ngu Lap Trinh Java
75/115
Array ca Arrays (2)
-
8/10/2019 Ng on Ngu Lap Trinh Java
76/115
Bi 4: Lp (Classes) v k tha(Inheritance)
-
8/10/2019 Ng on Ngu Lap Trinh Java
77/115
To lp
-
8/10/2019 Ng on Ngu Lap Trinh Java
78/115
Khai bo lpElement Function
@annotation(Optional) An annotation (sometimes called meta-
data)
public (Optional) Class is publicly accessible
abstract (Optional) Class cannot be instantiated
final (Optional) Class cannot be subclassed
classNameOfClass
Name of the class
(Optional) Comma-separated list of type variables
extends Super (Optional) Superclass of the class
implementsInterfaces
(Optional) Interfaces implemented by the class
{ ClassBody} Provides the class's functionality
-
8/10/2019 Ng on Ngu Lap Trinh Java
79/115
Khai bo Member Variables
Element Function
accessLevel (Optional) Access level for the variable
static (Optional) Declares a class variable
final(Optional) Indicates that the variable's value cannot
change
transient (Optional) Indicates that the variable is transient
volatile (Optional) Indicates that the variable is volatile
type name The type and name of the variable
-
8/10/2019 Ng on Ngu Lap Trinh Java
80/115
nh ngha Methods (1)
-
8/10/2019 Ng on Ngu Lap Trinh Java
81/115
nh ngha Methods (2)
Element Function
@annotation (Optional) An annotation (sometimes called meta-data)
accessLevel (Optional) Access level for the method
static (Optional) Declares a class method
(Optional) Comma-separated list of type variables.
abstract(Optional) Indicates that the method must be implementedin concrete subclasses.
final (Optional) Indicates that the method cannot be overridden
native
(Optional) Indicates that the method is implemented in
another languagesynchronized (Optional) Guarantees exclusive access to this method
returnTypemethodName
The method's return type and name
(paramList) The list of arguments to the method
throws exceptions (Optional) The exceptions thrown by the method
-
8/10/2019 Ng on Ngu Lap Trinh Java
82/115
nh ngha Constructors
Constructor c cng tn vi lp. Khng c kiu tr v. C hockhng c tham s.
public Stack() { }
public Stack(int size) {} Trong constructor, ta c th gi superclass constructor:
super([danh sch i s]); hoc constructor khc: this([danhsch i]). Nhng lnh ny, nu c, phi l lnh u tin trongconstructor.
T th h M th d
-
8/10/2019 Ng on Ngu Lap Trinh Java
83/115
Truyn tham s cho Methods,Constructors
Java truyn tham s bng gi tr: primitive type passed byvalue; cn li - passed by value of reference.
Java 1.5 cho php phng thc c th nhn mt s bt k thams (c gi l varargs).
public static Polygon polygonFrom(Point listOfPoints) {//listOfPoints kiu Point[]
}
System.out.printf(String format, Object args);
-
8/10/2019 Ng on Ngu Lap Trinh Java
84/115
Tr v gi tr t Methods
Lnh return .public boolean isEmpty() { return items.isEmpty(); }
Nu method khai bo kiu tr v l void, ta dng lnh return
khng c biu thc hoc l khng cn lnh return. Vi override method, kiu tr v c th l subclass ca kiu tr
v ca overrided method (covariant return type Java 1.5) chkhng cn phi ging hon ton.
-
8/10/2019 Ng on Ngu Lap Trinh Java
85/115
S dng t kha this
C ch khi ta cn truy cp n cc members ca lp m trongphm vi hin thi c bin trng tn:
public class HSBColor {
private int hue, saturation, brightness;public HSBColor (int hue, int saturation,
int brightness) {
this.hue = hue;
this.saturation = saturation;
this.brightness = brightness;
}
}
Ki t t b
-
8/10/2019 Ng on Ngu Lap Trinh Java
86/115
Kim sot truy cp n members calp
Ta s dng access modifier.class Point {
privateint x, y;
publicint getX() { return x;}}
Specifier Class Package Subclass World
private Y N N N
no specifier Y Y N N
protected Y Y Y N
public Y Y Y Y
M b i t b
-
8/10/2019 Ng on Ngu Lap Trinh Java
87/115
Members ca instance v membersca lp
Members ca instance: khng c t kha static. Chtruy cp c khi i tng c khi to.
Members ca lp: khai bo c t kha static. C thtruy cp trc tip qua tn lp.
class A {
public void instanceMethod() {}
public static void classMethod() {} }
A a = new A();
a.instanceMethod();a.classMethod();
A.classMethod();
Khi to members ca instance v
-
8/10/2019 Ng on Ngu Lap Trinh Java
88/115
Khi to members ca instance vmembers ca lp (1)
Khi to trc tip.private int i = 10;
private static int count = 0;
Khi to instance member qua constructor hocinitialization blockkhi lnh t do trong body caclass, c gi trc mi constructor:
{
i = 10;
}
Khi to members ca instance v
-
8/10/2019 Ng on Ngu Lap Trinh Java
89/115
Khi to members ca instance vmembers ca lp (2)
Khi to class member qua static initialization blockstatic {
count = 0;
}static initialization block c gi thc hin khi class
c np vo h thng.
-
8/10/2019 Ng on Ngu Lap Trinh Java
90/115
Qun l k tha
-
8/10/2019 Ng on Ngu Lap Trinh Java
91/115
Overriding v Hiding Methods
Mt instance method ca subclass vi cng ch k (signature)v return type vi instance method ca superclass c gi loverrides. Java 1.5 cho php kiu tr v ca override method lkiu con ca kiu tr v ca method lp cha (covariant returntype).
Instance method ch c th override bng mt instance method.Static method ch c th hide bng mt static method. Ngcli, pht sinh li compile.
-
8/10/2019 Ng on Ngu Lap Trinh Java
92/115
Hiding Member Variables
Ta c th nh ngha mt bin trong subclass trng tn vi bintrong superclass. Khi bin trong subclass s che bin trongsuperclass. truy cp n bin trong superclass phi dng:super.variableName.
-
8/10/2019 Ng on Ngu Lap Trinh Java
93/115
S dng t kha super
Ta s dng t kha super truy cp n cc phng thc,bin ca lp cha: super.memberName;
public class Superclass {public boolean aVariable;public void aMethod() { aVariable = true; } }
public class Subclass extends Superclass {public boolean aVariable; //hides aVariable in Superclasspublic void aMethod() { //overrides aMethod in Superclass
aVariable = false;super.aMethod();
System.out.format("%b%n", aVariable);System.out.format("%b%n", super.aVariable);}
}
-
8/10/2019 Ng on Ngu Lap Trinh Java
94/115
Final Class v Final Method
Ta khng th extends mt final class:public class final A {}public class B extends A {} //compile error
Ta khng th override mt final method:class A {final void finalMethod() {}
}
class B extends A {
void finalMethod() {} //compile error
}
-
8/10/2019 Ng on Ngu Lap Trinh Java
95/115
Abstract Method v Abstract Class
Abstract method: ch c khai bo, khng c body.abstract void draw();
Abstract class: khai bo vi t kha abstract.
public abstract class Figure {} Khi mt lp c 1 phng thc l abstract (hoc cha c
implement), n buc phi khai bo l abstract. (nhng ngc lith khng ng mt lp abstract c th khng c mt phngthc abstract no).
Nhng lp con c nhim v implements cc abstract methods. Ta khng th khi to object ca abstract class, ch c th khai
bo bin kiu abstract class.
-
8/10/2019 Ng on Ngu Lap Trinh Java
96/115
Nested Classes
-
8/10/2019 Ng on Ngu Lap Trinh Java
97/115
Cc loi nested class
Static nested class
Inner (non-static) class: new Parent().new Inner();
Local class
Anonymous class
Type Scope Inner
static nested class member no
inner [non-static]
class member yes
local class local yes
anonymous class only the point where it is defined yes
-
8/10/2019 Ng on Ngu Lap Trinh Java
98/115
Kiu lit k
-
8/10/2019 Ng on Ngu Lap Trinh Java
99/115
S lc v kiu lit k enum L tp hp c nh cc constants. Dng n gin nht:enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY };
-
8/10/2019 Ng on Ngu Lap Trinh Java
100/115
Li ch ca kiu lit k enum C th in ra tn c ngha. Typesafe
Namespace
S dng trong lnh switch Ta c th nh ngha thm methods, fields; implements
interface Implements Comparable, Serializable
Phng thc quan trng: values, name, ordinal, toString
Tm hiu thm: import static (Java 1.5), java.lang.Enum
-
8/10/2019 Ng on Ngu Lap Trinh Java
101/115
Bi 5: Giao din (Interfaces) vPackages
-
8/10/2019 Ng on Ngu Lap Trinh Java
102/115
To v s dng interface
-
8/10/2019 Ng on Ngu Lap Trinh Java
103/115
Interface l g?
Interface l mt tp hp cc method c khai bo nhngkhng c nh ngha
S khc nhau gia interface v abstract class: Interface khng th implement bt k phng thc no Class c th implement rt nhiu interface nhng ch c 1 super
class
Interface khng thuc mt class hierarchy Nhng lp khng c lin quan c th implements mt interface
-
8/10/2019 Ng on Ngu Lap Trinh Java
104/115
Khai bo mt interface
Interface default l abstract.
Tt c phng thc trong interface, default (and only) l publicabstract (khng th l static)
Tt c cc bin khai bo trong interface, default (and only) lpublic static final.
-
8/10/2019 Ng on Ngu Lap Trinh Java
105/115
Implement mt interface
Class c th implements 1 hoc nhiu interface. Cc interfaceny c khai bo sau mnh implements.
public class StockApplet extends Applet
implements StockWatcher{
}
S dng interface nh mt kiu
-
8/10/2019 Ng on Ngu Lap Trinh Java
106/115
S dng interfacenh mt kiutham chiu
Sau khi c nh ngha, interface c th c dng nh l mtkiu d liu (data type). Ta c th gn bin kiu interface bngmt instance ca class implements interface .
public class StockMonitor {
public void watchStock(StockWatcher watcher,
TickerSymbol tickerSymbol,
BigDecimal delta) {
...}
}
-
8/10/2019 Ng on Ngu Lap Trinh Java
107/115
Interface khng th m rng c
Nu ta thm phng thc mi vo interface, nhng class cimplement interface ny s b hng.
Ta ch c th nh ngha mt interface mi extends interface c,v nhng class mi s la chn dng interface mi hay
interface c.
-
8/10/2019 Ng on Ngu Lap Trinh Java
108/115
Static import
Ta c th import cc thnh phn static ca lp bng lnh:import static class.*; hoc import static class.memberName.
Sau trong chng trnh ta c th tham chiu n ccmember ny bng memberName.
import static java.lang.Math.*;
Ta c th truy cp n cc thnh phn static ch bng tn:PI, E, cos(), round()
-
8/10/2019 Ng on Ngu Lap Trinh Java
109/115
To v s dng package
-
8/10/2019 Ng on Ngu Lap Trinh Java
110/115
Th no l mt package?
Package l mt tp hp cc kiu (classes, interfaces, enums,annotations) c lin h vi nhau cung cp kh nng bo v truycp v qun l name space.
Nhc li: nhng access modifier default (khng khai bo g) ch
c th truy cp c vi nhng i tng trong cng package.
-
8/10/2019 Ng on Ngu Lap Trinh Java
111/115
Cch to mt package?
Dng t kha package ; trn u cc file trongpackage.
Lnh ny nu c phi l lnh u tin trong file.package graphics;
public class Circle extends Graphic implements Draggable {
. . .
}
-
8/10/2019 Ng on Ngu Lap Trinh Java
112/115
Cch t tn mt package?
Tn package s tng ng vi th mc cha file sau khi dch. Vvy tn package phi ph hp vi h thng file ca h iuhnh.
Package c th cha bn trong cc package v cc file khc.VD
package com.fpt.fss.fmt;
S dng cc members ca mt
-
8/10/2019 Ng on Ngu Lap Trinh Java
113/115
S dng cc members ca mtpackage
Ta dng lnh import. Cc lnh import nu c phi ng ngay sau lnh package.VD
package com.fpt.fss.fmt;import java.io.*;
Lnh import java.io.* ch import cc class, interface capackage java.io m khng import cc subpackage ca packagejava.io.
Nu xy ra xung t gia cc tn trong cc package, ta phi sdng tn y : .
-
8/10/2019 Ng on Ngu Lap Trinh Java
114/115
Qun l file ngun v file class (1)
-
8/10/2019 Ng on Ngu Lap Trinh Java
115/115
Qun l file ngun v file class (2)