Java 方法

创建于 2024-12-02 / 45
字体: [默认] [大] [更大]

method 方法是一个代码块,只在运行时调用。

可以将数据(称为参数)传递到方法中。

方法用于执行某些操作,它们也称为函数

为什么使用方法?代码复用:定义一次代码,然后多次使用。


创建一个方法

方法必须在类中声明。它是用方法的名称定义的,后跟括号()。Java提供了一些预定义的方法,如System.out.println(),但您也可以创建自己的方法来执行某些操作:

实例

在MyClass内创建一个方法:

public class MyClass {
  static void myMethod() {
    // 要执行的代码
  }
}

实例解析

  • myMethod() 是方法的名称
  • static 意味着该方法属于MyClass类,而不是MyClass类的对象。在本教程的后面部分,您将了解有关对象以及如何通过对象访问方法的更多信息。
  • void 表示此方法没有返回值。您将在本章后面了解有关返回值的更多信息

方法调用

要在Java中调用一个方法,请编写该方法的名称,后跟两个括号();

在下面的示例中,调用 myMethod() 用于打印文本(操作):

实例

main,调用myMethod()方法:

public class MyClass {
  static void myMethod() {
    System.out.println("I just got executed!");
  }

  public static void main(String[] args) {
    myMethod();
  }
}

// 输出 "I just got executed!"

运行实例 »

一个方法可以被多次调用:

实例

public class MyClass {
  static void myMethod() {
    System.out.println("I just got executed!");
  }

  public static void main(String[] args) {
    myMethod();
    myMethod();
    myMethod();
  }
}

// I just got executed!
// I just got executed!
// I just got executed!

运行实例 »

在下一章 Method Parameters 中,您将学习如何将数据(参数)传递到方法中。


学习训练

练习题:

插入缺少的部分以从 main 调用 myMethod

static void myMethod() {
  System.out.println("I just got executed!");
}

public static void main(String[] args) {
  ;
}

开始练习




0 人点赞过