Professional Documents
Culture Documents
lớp.
Thuật ngữ đối tượng (object) nhiều khi được dùng để
//real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
//real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
Chú ý: So sánh >, >=, <, <= chỉ áp dụng cho kiểu số. Không áp dụng được với
boolean, reference, String… Bởi vậy các biểu thức sau không hợp lệ:
false < true; “abc” < “bcd”; obj1 < obj2;
Conditional Operators
Operator Sử dụng Mô tả
&& op1 && op2 Trả về true nếu op1 và op2 true. Không lượng
giá op2 nếu op1 false
|| op1 || op2 Trả về true nếu op1 hoặc op2 true. Không
lượng giá op2 nếu op1 true
! !op Trả về true nếu op false
& op1 & op2 Trả về true nếu op1và op2 true. Luôn luôn
lượng giá op2. Thực hiện bitwise AND với 2
toán hạng số.
| op1 | op2 Trả về true nếu op1 hoặc op2 true. Luôn luôn
lượng giá op2. Thực hiện bitwise OR với 2
toán hạng số.
^ op1 ^ op2 Trả về true nếu op1 và op2 là khác nhau.
(XOR logic)
Shift Operators
Operator Sử dụng Mô tả
<< op1 << op2 Dịch trái op1 op2 bits.
>> op1 >> op2 Dịch phải op1 op2 bits. Lấp đầy bên bên trái
bằng bit dấu (Signed right shift).
>>> op1 >> op2 Dịch phải op1 op2 bits. Lấp đầy bên trái bằng
0 (Unsigned right shift).
Chú ý: Khi định nghĩa class, nếu ta không định nghĩa bất kỳ
constructor nào, java compiler sẽ tạo cho ta một default
constructor không có tham số, cùng access modifier với class.
Sử dụng đối tượng
Tham chiếu đến biến của đối tượng (qualified name):
objectReference.variableName
Gọi phương thức của đối tượng:
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ó thêm hạn chế: nếu
subclass ở package khác, chỉ có thể truy cập đến protected
members của đối tượng hiện thời.
+ public: all classes.
Thu hồi những đối tượng không còn
sử dụng
Đối tượng không còn được sử dụng khi các tham chiếu đến nó
ra khỏi phạm vi hoặc không còn tham chiếu đến nó:
Point pt = new Point(0, 0); pt = null;
Java tự động thu hồi những đối tượng không còn được sử dụng
– garbage collection.
Ta có thể thúc đẩy garbage collection bằng: System.gc() hoặc
Runtime.gc().
Ta không thể khẳng định được khi nào một đối tượng sẽ bị thu
hồi.
Character
Static methods của lớp Character
Method Description
int indexOf(int) Returns the index of the first (last) occurrence of the
int lastIndexOf(int) specified character.
int indexOf(String) Returns the index of the first (last) occurrence of the
int lastIndexOf(String) specified string.
Method Description
Replaces all occurrences of the character specified as the
String replace(char, first argument with the character specified as the second
char) argument. If no replacements are necessary, the original
string object is returned.
String replaceAll(String
Replaces each substring of this string that matches the
regex, String
specified regular expression.
replacement)
So sánh Strings, từng phần trong
String
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)
String trim()
String toLowerCase()
String toUpperCase()
Thao tác trên StringBuilder,
StringBuffer
StringBuffer insert(int, boolean)
StringBuffer insert(int, char)
StringBuffer append(boolean)
StringBuffer insert(int, char[])
StringBuffer append(char)
StringBuffer insert(int, char[], int,
StringBuffer append(char[])
int)
StringBuffer append(char[], int, int)
StringBuffer insert(int, double)
StringBuffer append(double)
StringBuffer insert(int, float)
StringBuffer append(float)
StringBuffer insert(int, int)
StringBuffer append(int)
StringBuffer insert(int, long)
StringBuffer append(long)
StringBuffer insert(int, Object)
StringBuffer append(Object)
StringBuffer insert(int, String)
StringBuffer append(String)
StringBuffer replace(int, int, String)
void setCharAt(int, char)
StringBuffer delete(int, int)
StringBuffer deleteCharAt(int) StringBuffer reverse()
Number
Number classes
Những method chung của lớp
Number
Method Description
byte byteValue()
short shortValue()
int intValue() Convert the value of this number object to the primitive
long longValue() data types of byte, short, int, long, float, and double.
float floatValue()
double doubleValue()
Constant Description
Float.NEGATIVE_INFINITY
The negative infinity value for a float or a double.
Double.NEGATIVE_INFINITY
Float.POSITIVE_INFINITY
The positive infinity value for a float or a double.
Double.POSITIVE_INFINITY
Chuyển từ String sang Number
Sử dụng phương thức static của wrapper class (Byte, Integer,
Double, Float, Long, Short): valueOf – return wrapper type.
Ví dụ:
float f = Float.valueOf(“9.3”).floatValue();
double d = Double.valueOf(“9.3e2”).doubleValue();
Chuyển từ Number sang String
Có 3 cách:
Dùng toán tử gép xâu với xâu “”.
Dùng phương thức static String.valueOf(primitive).
Dùng phương thức static toString(primitive) của các lớp: Byte,
Short, Integer, Long, Float, Double.
Ví dụ:
int i;
String s1 = “” + i;
String s2 = String.valueOf(i);
String s3 = Integer.toString(i);
Những phép toán số học nâng cao
Method of Math
Description
class
double abs(double)
float abs(float)
Trả về giá trị tuyệt đối
int abs(int)
long abs(long)
double ceil(double) Trả về giá trị nguyên lớn nhất nhỏ hơn đối số
double floor(double) Trả về giá trị nguyên nhỏ nhất lớn hơn đối số
private Y N N N
no specifier Y Y N N
protected Y Y Y N
public Y Y Y Y
Members của instance và members
của lớp
Members của instance: không có từ khóa static. Chỉ
truy cập được khi đối tượng được khới tạo.
Members của lớp: khai báo có từ khóa static. Có thể
truy cập trực tiếp qua tên lớp.
class A {
public void instanceMethod() {}
public static void classMethod() {} }
A a = new A();
a.instanceMethod();
a.classMethod();
A.classMethod();
Khởi tạo members của instance và
members của lớp (1)
Khởi tạo trực tiếp.
private int i = 10;
private static int count = 0;
Khởi tạo instance member qua constructor hoặc
initialization block – khối lệnh tự do trong body của
class, được gọi trước mỗi constructor:
{
i = 10;
}
Khởi tạo members của instance và
members của lớp (2)
Khởi tạo class member qua static initialization block
static {
count = 0;
}
static initialization block được gọi thực hiện khi class
được nạp vào hệ thống.
Quản lý kế thừa
Overriding và Hiding Methods
Một instance method của subclass với cùng chữ ký (signature)
và return type với instance method của superclass được gọi là
overrides. Java 1.5 cho phép kiểu trả về của override method là
kiểu con của kiểu trả về của method lớp cha (covariant return
type).
Instance method chỉ có thể override bằng một instance method.
Static method chỉ có thể hide bằng một static method. Ngược
lại, phát sinh lỗi compile.
Hiding Member Variables
Ta có thể định nghĩa một biến trong subclass trùng tên với biến
trong superclass. Khi đó biến trong subclass sẽ che biến trong
superclass. Để truy cập đến biến trong superclass phải dùng:
super.variableName.
Sử dụng từ khóa super
Ta sử dụng từ khóa super để truy cập đến các phương thức,
biến của lớp 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 Superclass
public void aMethod() { //overrides aMethod in Superclass
aVariable = false;
super.aMethod();
System.out.format("%b%n", aVariable);
System.out.format("%b%n", super.aVariable);
}
}
Final Class và Final Method
Ta không thể extends một final class:
public class final A {…}
public class B extends A {…} //compile error
Ta không thể override một final method:
class A {
final void finalMethod() {}
}
class B extends A {
void finalMethod() {} //compile error
}
Abstract Method và Abstract Class
Abstract method: chỉ có khai báo, không có body.
abstract void draw();
Abstract class: khai báo với từ khóa abstract.
public abstract class Figure {}
Khi một lớp có 1 phương thức là abstract (hoặc chưa được
implement), nó buộc phải khai báo là abstract. (nhưng ngược lại
thì không đúng – một lớp abstract có thể không có một phương
thức abstract nào).
Những lớp con có nhiệm vụ implements các abstract methods.
Ta không thể khởi tạo object của abstract class, chỉ có thể khai
báo biến kiểu abstract class.
Nested Classes
Các loại nested class
Static nested class
Inner (non-static) class: new Parent().new Inner();
Local class
Anonymous class