同一个类里不同方法之间相互调用时,可以直接调用代码
时间: 2024-03-03 18:50:45 浏览: 21
在同一个类里,不同方法之间是可以相互调用的。如果一个方法需要使用另一个方法中定义的变量或实现的功能,可以直接在方法内部调用另一个方法。在Java中,方法的调用遵循一定的规则,可以使用以下方式来调用另一个方法:
1. 直接调用:在当前方法内部直接使用方法名来调用另一个方法。
2. 使用this关键字调用:在当前方法内部使用this关键字来调用同一个类的其他方法。
3. 使用类名调用:在当前方法内部使用类名来调用同一个类的静态方法。
下面是一个示例代码,演示了在同一个类中不同方法之间如何相互调用:
```java
public class MyClass {
private int num;
public void setNum(int num) {
this.num = num;
}
public void method1() {
System.out.println("method1 is called.");
method2(); // 直接调用method2
}
public void method2() {
System.out.println("method2 is called.");
method3(); // 使用this关键字调用method3
}
public void method3() {
System.out.println("method3 is called.");
MyClass.method4(); // 使用类名调用静态方法method4
System.out.println("num = " + num);
}
public static void method4() {
System.out.println("method4 is called.");
}
}
// 在主程序中调用方法
MyClass obj = new MyClass();
obj.setNum(100);
obj.method1();
```
在上面的示例代码中,我们定义了一个名为 `MyClass` 的类,其中包含了四个方法:`setNum`、`method1`、`method2` 和 `method3`。在 `method1` 中,我们直接调用了 `method2`;在 `method2` 中,我们使用了 `this` 关键字调用了 `method3`;在 `method3` 中,我们使用了类名来调用了静态方法 `method4`。在主程序中,我们先创建了一个 `MyClass` 的对象,并通过 `setNum` 方法设置了 `num` 的值为100,然后调用了 `method1` 方法。运行程序后,会依次输出 `method1 is called.`、`method2 is called.`、`method3 is called.`、`method4 is called.` 和 `num = 100`。