Java Basics Part 17/20 - Methods
目錄
方法是語句的集合,用來執行一個操作。比如調用 System.out.println() 方法時,系統實際上是執行了一些語句,從而把一條消息顯示到控制檯。
下面就將學習在程序設計中怎樣創建一個有或者無返回值的方法,怎樣調用有或者無形參的方法,以及運用方法抽象。
方法創建
用一個例子來解釋方法的語法:
public static int methodName(int a, int b) {
// body
}
- public static: 修飾符
- int: 返回類型
- methodName: 就是方法名稱咯
- a, b: 形參列表
方法的定義含有方法頭和方法體,形式如下:
modifier returnType nameOfMethod (Parameter List) {
// method body
}
語法解釋:
- modifier: 定義了方法的訪問類型,可選
- returnType: 定義了方法的可能的返回類型
- nameOfMethod: 方法名。方法簽名包含了方法名和參數列表
- Parameter List: 參數列表:參數的類型,順序,個數。這些都是可選的
- method body: 語句的集合
舉例:
/** the snippet returns the minimum between two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
方法調用
方法的調用有兩個結果:返回值和不返回值。
方法的調用很簡單,當程序調用方法時,程序就把控制權交給了被調用的方法,這個方法在下面兩種情況下會把控制權返還給調用者:
- 執行了 return 語句
- 到達了方法的末尾
舉例:
下面的例子演示了方法的創建和調用
public class ExampleMinNumber{
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
// output
inimum value = 6
void 關鍵字
如果方法不返回值,那麼就用 void 關鍵字吧
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}
else if (points >= 122.4) {
System.out.println("Rank:A2");
}
else {
System.out.println("Rank:A3");
}
}
}
// output
Rank:A1
參數傳值
參數可以傳值或者引用。
下面演示傳值的方法
public class swappingExample {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " +
a + " and b = " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " +
a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a
+ " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a
+ " b = " + b);
}
}
// output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45
方法重載
重載,是一個類中有 2 個 或多於 2 個的同名但參數不同的方法。重載與重寫不同,重寫指的是類與子類的關係,重寫的方法與原方法完全相同。
舉例
public class ExampleOverloading{
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
// output
inimum Value = 6
inimum Value = 7.3
使用命令行參數
有時候有從外部給程序傳遞參數的需求。這個時候就要通過給 main() 傳遞命令行參數。
命令行參數是緊跟在程序名稱的信息。這些參數存儲在 mian() 的 String[] 參數中。
public class CommandLine {
public static void main(String args[]){
for(int i=0; i<args.length; i++){
System.out.println("args[" + i + "]: " +
args[i]);
}
}
}
// execute
$java CommandLine this is a command line 200 -100
// output
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
構造器
當創建對象的時候,構造器負責初始化對象。構造器的名字與類名一樣。但是,構造器沒有顯示的返回值。
通常,通過構造器給實例變量賦初值,或者用它來創建對象。
所有的類都有構造器,即使不顯示定義,Java 也會自動提供一個默認的構造器。但是一旦有了自定義的構造器,默認的構造器就不會創建了。
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass() {
x = 10;
}
}
// call the constructor
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
參數化的構造器
最一般的情形是需要構造器接收 1 個 或 多個 參數。構造器接收參數和方法接收參數是一樣的。
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
// call the constructor
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
// output
10 20
this 關鍵字
this 關鍵字一般用在實例方法或者構造器中,用來引用當前類的對象。使用 this,可以引用類的成員,比如構造器,變量和方法。
this 只能用在實例方法或者構造器中
通常情況下,this 用來:
在構造器或者方法中,用來區分同名的局部變量和實例變量
class Student { int age; Student(int age){ this.age=age; } }
在同一個類中,一個構造器調用其他構造器時。
class Student{ int age Student(){ this(20); } Student(int age){ this.age=age; } }
舉例:
這個例子使用 this 來訪問類的成員。
public class This_Example {
//Instance variable num
int num=10;
This_Example(){
System.out.println("This is an example program on keyword this ");
}
This_Example(int num){
//Invoking the default constructor
this();
//Assigning the local variable num to the instance variable num
this.num=num;
}
public void greet(){
System.out.println("Hi Welcome to Tutorialspoint");
}
public void print(){
//Local variable num
int num=20;
//Printing the instance variable
System.out.println("value of local variable num is : "+num);
//Printing the local variable
System.out.println("value of instance variable num is : "+this.num);
//Invoking the greet method of a class
this.greet();
}
public static void main(String[] args){
//Instantiating the class
This_Example obj1=new This_Example();
//Invoking the print method
obj1.print();
//Passing a new value to the num variable through parametrized constructor
This_Example obj2=new This_Example(30);
//Invoking the print method again
obj2.print();
}
}
// output
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint
變長參數
JDK 1.5 引入了變長參數,可以給方法傳遞不定數量的同一種類型的參數。
聲明如下:
typeName... parameterName
變長參數必須在方法參數列表的最後一個。
舉例:
public class VarargsDemo {
public static void main(String args[]) {
// Call method with variable args
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
}
// output
The max value is 56.5
The max value is 3.0
finalize() 方法
有可能需要定義一個在對象的被銷燬之前由垃圾回收器調用的方法。這個方法就是 finalize()。它可以用來確保對象被完全清除。
比如,可能會使用 finalize() 來確保打開的資源文件對象被關閉。
只需要在類中定義一個 finalize(),就算是給類添加了一個 finalizer (終結器?)。Java 運行時會在銷燬對象之前調用它。
protected void finalize() {
// finalization code here
}
這裏使用 protected,是爲了防止類的外部直接訪問到 finalize()。
但是 finalize() 方法不確定會何時執行。例如,程序在垃圾回收之前就結束了,那麼finalize() 就不會執行。