在method的block內有許多程式碼,當method被呼叫的時候,這些程式碼就會被執行method如果有return value(回傳值)則須在method名稱前加上return value的資料類型。即使method沒有return value,也須在method名稱前加上void。範例如下
[Method_ReturnValue.java]
class Cube {
String name;
double length;
double width;
double height;
double volume() {
return length * width * height;
}
}
class Method_ReturnValue{
public static void main(String argv[]) {
Cube box1 = new Cube();
box1.name = "1號箱子";
box1.length = 5.0;
box1.width = 3.0;
box1.height = 2.0;
if(box1.volume() <= 50)
System.out.println("空間足夠");
else
System.out.println("空間不夠");
}
}
method可以設定argument(參數)以處理更複雜的情況,範例如下
[Method_Argument.java]
class Cube{
String name;
double length;
double width;
double height;
double volume() {
return length * width * height;
}
double volume(Cube cube) //多載(overload) {
return volume() + cube.volume();
}
}
class Method_Argument{
public static void main(String argv[]) {
Cube box1 = new Cube();
box1.name = "1號箱子";
box1.length = 5.0;
box1.width = 3.0;
box1.height = 2.0;
Cube box2 = new Cube();
box2.name = "2號箱子";
box2.length = 6.0;
box2.width = 3.0;
box2.height = 2.0;
System.out.println("總體積為" + box1.volume(box2));
}
}
但要注意所傳的argument是屬於primitive type還是reference,範例如下
[ArgumentPass.java]
class ArgumentPass{
public void update(int i){i++;}
public void update(int x[]){x[0]++;}
public static void main(String args[]) {
ArgumentPass arg = new ArgumentPass();
int j = 1;
int y[] = {1,2,3};
arg.update(j);
arg.update(y);
System.out.println(j);
System.out.println(y[0]);
}
}
result:
1
2
primitive type 屬於call by value, 而 Array 則屬與reference type,是call by reference。
0 comments:
張貼留言