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

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.