String Greeting = "Hello";運算:
String s = Greeting.substring(0,4);每一物件必須屬於某一類別(class)。
類別 : 可由用者定的資料型式。
例如,造一類別為 Time 的物件 millennium,千禧年元旦:
Time millennium = new Time(2000, 1,1,0,0,0);
此例中, new 用以創造一個新物件。 Time(...) 是類別 Time 的建構器(constructor), 用以設定物件的初值,初值列在括弧中,共有六個,分別表示年、月、日、時、分、秒。
注意:建構器的名稱和類別相同(此例名稱都是Time)。
Time now = new Time();
Time() 沒有參數,是類別預設的建構器,其參數初值採用預設值。
object.function(parameters)例如,
now.addSeconds(1000);
讀取儲存在物件中的現值,則用方法 getXXX(), XXX 為物件內儲的資料名稱,Time 有 Year, Month, Day, Hours, Minutes, 和 Seconds 六項。
例如,Time 有
getSeconds() getMinutes() getHours() getDay() getMonth() getYear()例題:
SET CLASSPATH = %CLASSPATH%;C:\JAVA\CS1package ccj 的安裝說明,在 install.htm。
例題:EmployeeTest.java
此例利用 ccj 中的類別 Employee。
Employee 是用者界定的類別,內儲員工的資料有 name 和 salary 兩項。
主要的 implementation 如下:
public class Employee { public Employee(String n, double s) { // constructor name = n; salary = s; } public Employee() { // default constructor name = ""; salary = 0; } public String getName() { return name; } public double getSalary() { return salary; } public void setSalary(double s) { salary = s; } ... private String name; // data private double salary; // data }
Input | Output | Usage | |
Console Application | keyboard | text | standalone |
Graphics Applet | keyboard/mouse | graphical | need browser/viewer |
文字模式的程式基本架構:
public class MyProg { public static void main(String[] args) { your code goes here }圖形模式的程式,可用小程式的方式,其基本架構:
public class MyProg extends GraphicsApplet { public void run() { your code goes here }GraphicsApplet 是屬於類別 Applet,提供寫圖形程式所需的基本架構,是 ccj 中的一個類別。 顯示小程式的結果時,必須另編一HTML檔(例如 HelloWeb.html), 說明小程式的名稱及顯示所需寬度和高度。 例如, HelloWeb.html 含有下列 HTML tags,就可利用 appletviewer 或綱頁瀏覽器(browser) 顯示圖形。
<applet code = "HelloWeb.class" width=150 height=50></applet>
例題:
String name = readString("Please type your name:"); int age = readInt("Please type your name:");
Point p = new Point(0,0); Point q = (Point) p.clone(); // Point q = p; 只抄 reference String b = ""; // 空字串 String c = null; // 沒有字串