物件雖然是獨立的個體,但不同的物件可以擁有相同的屬性及方法,所以,不同的物件若擁有共同的屬性,但因為屬性內容的不同,因此可以創造出同類性質但卻獨立的不同物件。而同類型的物件,則構成了類別(Class)。
事實上,在實際的物件導向程式設計中(例如Java),我們必須先定義類別,然後才能夠透過類別宣告各個屬於該類別下的物件,接著再設定物件的屬性來代表該物件某方面的特性,並使用物件的方法來操作物件。
Java規定公共類別(public class)必須寫在該公共類別名稱的.java檔案內, 例如public class Example就必須寫在Example.java這個檔案內。Example.java裡面也可以定義其他的類別,但是只有class Example能夠宣告為public,其他Example.java裡的class都不能宣告為public。當Java Virtual Machine啟動時,它會去找命令列上所指定的class裡的public static void main(String[] argv)方法,當做是程式的進入點。這有點像是C語言的main, 不同處在於每個java class都可以定義自己的public static void main(String[] argv)。
java Example
啟動上述的JVM時, JVM會去執行class Example裡的public static void main(String[] argv)。以下範例Example.java說明如何定義Java的class。
class Vehicle {
private int speed; // Object Variable
private String direction; // Object Variable, direction is a reference to String Object
private static int numVehicle = 0; // Class Variable
public Vehicle() { // Constructor, called when new a Object
this(0,"north"); // call another constructor to do initialization
}
public Vehicle(int s, String dir) { // Another Constructor. Use overloading to define two constructors
float speed; // define a local variable
speed = s; // the speed here refers to the above local variable
this.speed = s; // If we want to set object variable, use this.speed to refer object variable speed
direction = dir; // dir is a reference to object, not the object itself
numVehicle++; // increase the Vehicle number
}
protected void finalize() { // Destructor, called when the object is garbage collected by JVM
System.out.println("finalize has been called");
numVehicle--;
}
void setSpeed(int newSpeed) { // Object Method
this.speed = newSpeed;
}
void setDir(String dir) { // Object Method
this.direction = dir;
}
int getSpeed() { // Object Method
return speed;
}
String getDir() { // Object Method
return direction;
}
public static int totalVehicle() { // Class Method
return numVehicle;
}
}
public class Example {
public static void main(String[] argv) {
Vehicle v1 = new Vehicle(50, "west"); // new 敘述用來產生物件. 物件產生時需要呼叫Constructor來初始化物件
Vehicle v2;
v1.setSpeed(30);
v1.setDir("north");
System.out.println("V1: speed is "+v1.getSpeed()+", direction is "+v1.getDir()+".\n");
v2 = new Vehicle(40, "south");
System.out.println("There are "+Vehicle.totalVehicle()+" Vehicles in the world.\n");
v1 = v2; // let reference v1 point to where v2 is pointing
System.out.println("V1: speed is "+v1.getSpeed()+", direction is "+v1.getDir()+".\n");
System.gc(); // force system to do garbage collection, the object previously pointed by v1 shall be destroyed
System.out.println("There are "+Vehicle.totalVehicle()+" Vehicles in the world.\n");
}
}