Java 类方法

使用对象访问方法

实例

创建名为 myCar 的 Car 对象。调用 myCar 对象上的 fullThrottle() 和 speed() 方法,并运行程序:

// 创建 Main 类

public class Main {

// 创建 fullThrottle() 方法

public void fullThrottle() {

System.out.println("这辆车正以最快的速度行驶!");

}

// 创建 speed() 方法并添加参数

public void speed(int maxSpeed) {

System.out.println("最高速是:" + maxSpeed);

}

// 在 main 中,调用 myCar 对象上的方法

public static void main(String[] args) {

Main myCar = new Main(); // 创建 myCar 对象

myCar.fullThrottle(); // 调用 fullThrottle() 方法

myCar.speed(200); // 调用 speed() 方法

}

}

// 这辆车正以最快的速度行驶!

// 最高速是:200

亲自试一试

例子解释

1) 我们使用 class 关键字创建了一个自定义的 Main 类。

2) 我们在 Main 类中创建了 fullThrottle() 和 speed() 方法。

3) fullThrottle() 方法和 speed() 方法在调用时会打印出一些文本。

4) speed() 方法接受一个名为 maxSpeed 的 int 参数 - 我们将在 8) 中使用它。

5) 为了使用 Main 类及其方法,我们需要创建 Main 类的对象。

6) 然后,转到 main() 方法,您现在知道它是运行程序的内置 Java 方法(执行 main 中的任何代码)。

7) 通过使用 new 关键字,我们创建了名为 myCar 的对象。

8) 然后,我们在 myCar 对象上调用 fullThrottle() 和 speed() 方法:使用对象的名称(myCar),后跟一个点(.),后跟方法的名称(fullThrottle(); 和 speed(200);)。请注意,我们在 speed() 方法中添加了一个 int 参数 200。

请记住

点 (.) 用于访问对象的属性和方法。

如需在 Java 中调用方法,请写:方法名称,后跟一组括号 (),后跟分号 (;)。

类必须具有匹配的文件名(Main 和 Main.java)。