Java 中返回类型的重要性?

javaobject oriented programmingprogramming更新于 2024/7/26 10:22:00

return 语句使程序控制权转移回方法的调用者。Java 中的每个方法都声明有返回类型,并且对于所有 Java 方法来说,返回类型都是必需的。返回类型可以是原始类型,如 int、float、double引用类型void类型(不返回任何内容)。

关于返回值,有几件重要的事情需要了解

  • 方法返回的数据类型必须与方法指定的返回类型兼容。例如,如果某个方法的返回类型是布尔值,我们就不能返回整数。
  • 接收方法返回值的变量也必须与为该方法指定的返回类型兼容。
  • 参数可以按顺序传递,并且方法必须按相同顺序接受它们。

示例 1

public class ReturnTypeTest1 {
   public int add() { // 无参数
      int x = 30;
      int y = 70;
      int z = x+y;
      return z;
   }
   public static void main(String args[]) {
      ReturnTypeTest1 test = new ReturnTypeTest1();
      int add = test.add();
      System.out.println("The sum of x and y is: " + add);
   }
}

输出

The sum of x and y is: 100

示例2

public class ReturnTypeTest2 {
   public int add(int x, int y) { // with arguments
      int z = x+y;
      return z;
   }
   public static void main(String args[]) {
      ReturnTypeTest2 test = new ReturnTypeTest2();
      int add = test.add(10, 20);
      System.out.println("The sum of x and y is: " + add);
   }
}

输出

The sum of x and y is: 30

相关文章