Java程式示例:無引數無返回值的方法


首先,讓我們瞭解語法和示例,最後是實現。

Java中的方法非常重要,因為它允許程式碼重用,減少了程式碼中需要編寫的語句數量。

為了使方法可執行,方法主要包含三個部分。

  • 方法宣告。

  • 方法定義。

  • 方法呼叫。

方法呼叫是最後一步,而前兩步可以互換。這裡唯一需要注意的是,必須在呼叫方法之前宣告該方法。

語法

要建立一個沒有任何引數和返回值的方法,請參考以下語法。

Class class_name{
   function _name() {
      Statement 1;
      Statement 2;
      .
      .
      Statement n;
      //an optional return 
      return;
   }
   Main function() {
      // invoking the above function
      function_name();
   }
}

在類中建立一個具有空引數列表的方法。在方法內部編寫語句,後面可以跟一個空返回語句。這樣建立的方法在主方法中呼叫。

示例

下面的程式演示瞭如何建立一個既沒有引數也沒有返回值的方法。

建立一個名為Wish的類,在這個類中,建立一個名為wish()、返回型別為void的方法,表示它不返回任何值,也不包含任何引數。在wish()方法中編寫一條語句,並在主方法中呼叫此方法來顯示。

// Java Program to demonstrate a method without Parameters and Return Type
public class Wish {
	// Declaration and Definition of the method
	public static void wish(){
		System.out.println("Good Morning! Have a nice day");
	}
	public static void main(String args[]){
		// Calling the method without any parameters
		wish ();
	}
}

輸出

Good Morning! Have a nice day

示例

下面的程式演示瞭如何建立一個既沒有引數也沒有返回值的方法。

建立一個名為Wish的類,在這個類中,建立一個名為wish()、返回型別為void的方法,表示它不返回任何值,也不包含任何引數。透過在主方法中呼叫該方法來顯示在wish()方法中編寫的語句。

// Java Program to demonstrate a method without Parameters and Return Type
public class Wish {
	// Declaration and Definition of the method
	public static void wish(){
		System.out.println("Congratulations! Have a great professional life");
			//It is optional to use a return statement here.
			return;
	}
	public static void main(String args[]){
		// Calling the method without any parameters
		wish();
	}
}

輸出

Congratulations! Have a great professional life

結論

本文闡述瞭如何在Java中定義一個沒有任何引數和返回值的方法。我們從語法開始,然後透過一個示例和兩個Java程式來清晰地說明這個主題。

更新於:2023年4月11日

瀏覽量:356

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告