2010年7月22日 星期四

Java Basic 之一

Class(類別) 種類~
public: can be used by anyone (even outside of the package)
(none): can be used within this package
abstract: 代表類別內有尚未實做的method
final: 代表此類別不能被別人 inherit

method 範圍種類~
public: can be accessed by anyone (even outside of the package)
protected: can be accessed within this package, **[also... subclass can accessed it even not in the same package]**
(none): can be accessed within this package.
private: can be accessed only by this class.
method 特性種類~
static: 靜態method, 不用被new就可使用
final: 不能被subclass override.
abstract: 只有宣告沒有實體程式的method, child class可以自己寫程式碼.
native: 代表method是用別的程式語言寫成的 (非JAVA)
synchronized: 此method有multi-threads的共用資料, 需被“Monitor” 機制控管.

variable 種類~
static: 靜態變數 (can be used as Class.XXX)
final: 不能改變的值
transient: 暫存變數 (在Object Serialization時, 此變數不存入Hard Drive)
volatile: 迅變變數 (宣告此變數為多工處理的共用變數。Java VM 會保證 volatile 變數安全地被各 client program 存取)

Overloading~
一個Class(類別)擁有一個以上的同名method(函式),稱為 overloading.
ex:
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}

class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
}


Overriding~
ex:
// Method overriding
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}

class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}

class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

沒有留言:

張貼留言