Java 教程

Java 控制語句

面向物件程式設計

Java 內建類

Java 檔案處理

Java 錯誤與異常

Java 多執行緒

Java 同步

Java 網路

Java 集合

Java 介面

Java 資料結構

Java 集合演算法

高階 Java

Java 雜項

Java API 與框架

Java 類參考

Java 有用資源

Java - 方法



Java 方法

Java 方法是語句的集合,這些語句組合在一起以執行操作。例如,當您呼叫 System.out.println() 方法時,系統實際上會執行幾個語句才能在控制檯上顯示訊息。

在本教程中,我們將學習如何在有或沒有返回值的情況下建立自己的方法,如何在有或沒有引數的情況下呼叫方法,以及如何在程式設計中應用方法抽象。

建立 Java 方法

要建立 Java 方法,應該有一個 訪問修飾符 後跟返回型別、方法名稱和引數列表。

建立 Java 方法的語法

考慮以下示例來解釋方法的語法 -

modifier returnType nameOfMethod (Parameter List) {
   // method body
}

上面顯示的語法包括 -

  • 修飾符 - 它定義了方法的訪問型別,使用它是可選的。

  • 返回型別 - 方法可能返回一個值。

  • 方法名 - 這是方法名稱。方法簽名由方法名稱和引數列表組成。

  • 引數列表 - 引數列表,它是方法的引數型別、順序和數量。這些是可選的,方法可能包含零個引數。

  • 方法體 - 方法體使用語句定義方法的作用。

建立 Java 方法的示例

這是上面定義的名為 minFunction() 的方法的原始碼。此方法接受兩個引數 n1n2,並返回兩者之間的最小值 -

/** 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; 
}

呼叫 Java 方法

要使用方法,應呼叫它。呼叫方法有兩種方式,即方法返回值或不返回值(無返回值)。

方法呼叫的過程很簡單。當程式呼叫一個方法時,程式控制權會轉移到被呼叫的方法。然後,此被呼叫的方法在兩種情況下將控制權返回給呼叫方,當 -

  • 執行 return 語句。
  • 它到達方法結束的閉合大括號。

返回 void 的方法被認為是對語句的呼叫。讓我們考慮一個例子 -

System.out.println("This is tutorialspoint.com!");

返回值的方法可以透過以下示例理解 -

int result = sum(6, 9);

示例:定義和呼叫 Java 方法

以下示例演示瞭如何定義方法以及如何呼叫它 -

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; 
   }
}

輸出

Minimum value = 6

Java 方法中的 void 關鍵字

void 關鍵字允許我們建立不返回值的方法。這裡,在下面的示例中,我們正在考慮一個 void 方法 methodRankPoints。此方法是一個 void 方法,它不返回任何值。對 void 方法的呼叫必須是一個語句,即 methodRankPoints(255.7);。它是一個 Java 語句,以分號結尾,如下面的示例所示。

示例:在方法中使用 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");
      }
   }
}

輸出

Rank:A1

在 Java 方法中按值傳遞引數

在呼叫過程中,需要傳遞引數。這些引數的順序應與其在方法規範中相應引數的順序相同。引數可以按值傳遞或按引用傳遞。

按值傳遞引數意味著用引數呼叫方法。透過這種方式,引數值將傳遞給引數。

示例:按值傳遞引數

以下程式顯示了一個按值傳遞引數的示例。即使在方法呼叫之後,引數的值也保持不變。

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);
   }
}

輸出

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

Java 方法過載

當一個類有兩個或多個同名但引數不同的方法時,稱為方法過載。它不同於覆蓋。在覆蓋中,方法具有相同的方法名稱、型別、引數數量等。

讓我們考慮前面討論的查詢整數型別最小數字的示例。如果,假設我們要查詢雙精度型別的最小數字。然後將引入過載的概念來建立兩個或多個具有相同名稱但引數不同的方法。

以下示例說明了這一點 -

示例:Java 中的方法過載

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; 
   }
}

輸出

Minimum Value = 6
Minimum Value = 7.3

過載方法使程式更易讀。這裡,給出了兩個同名但引數不同的方法。結果是整數和雙精度型別中的最小值。

使用命令列引數

有時您希望在執行程式時將一些資訊傳遞給程式。這是透過向 main( ) 傳遞命令列引數來實現的。

命令列引數是在執行程式時,在命令列上緊跟在程式名稱後面的資訊。在 Java 程式內部訪問命令列引數非常容易。它們作為字串儲存在傳遞給 main( ) 的 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]);
      }
   }
}

嘗試按如下所示執行此程式 -

$java CommandLine this is a command line 200 -100

輸出

args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

Java 方法內部的 this 關鍵字

this 是 Java 中的一個關鍵字,在例項方法或建構函式中用作對當前類物件的引用。使用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;	
   }
}

示例:在 Java 方法中使用 this 關鍵字

這是一個使用this關鍵字訪問類成員的示例。將以下程式複製並貼上到名為This_Example.java的檔案中。

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 <i>num</i> to the instance variable <i>num</i>
      this.num = num;	   
   }
   
   public void greet() {
      System.out.println("Hi Welcome to Tutorialspoint");
   }
      
   public void print() {
      // Local variable num
      int num = 20;
      
      // Printing the local variable
      System.out.println("value of local variable num is : "+num);
      
      // Printing the instance 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(); 
   }
}

輸出

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

Java 方法可變引數 (var-args)

JDK 1.5 使您能夠將相同型別的可變數量的引數傳遞給方法。方法中的引數宣告如下 -

typeName... parameterName

在方法宣告中,您指定型別後跟省略號 (...)。在一個方法中只能指定一個可變長度引數,並且此引數必須是最後一個引數。任何常規引數都必須位於它之前。

示例:使用可變引數 (var-args)

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);
   }
}

輸出

The max value is 56.5
The max value is 3.0

finalize( ) 方法

可以定義一個方法,該方法將在垃圾回收器最終銷燬物件之前被呼叫。此方法稱為finalize( ),可用於確保物件乾淨地終止。

例如,您可以使用 finalize( ) 來確保關閉該物件擁有的開啟檔案。

要向類新增終結器,只需定義 finalize( ) 方法即可。Java 執行時在即將回收該類的物件時會呼叫該方法。

在 finalize( ) 方法中,您將指定在物件銷燬之前必須執行的操作。

finalize( ) 方法具有以下通用形式 -

protected void finalize( ) {
   // finalization code here
}

這裡,關鍵字 protected 是一個說明符,它阻止類外部定義的程式碼訪問 finalize( )。

這意味著您無法知道何時甚至是否會執行 finalize( )。例如,如果您的程式在垃圾回收發生之前結束,則不會執行 finalize( )。

廣告