温馨提示×

java类怎么调用自己的方法

小亿
86
2024-04-26 14:11:41
栏目: 编程语言

在Java中,可以通过this关键字来调用当前对象的方法。this关键字代表当前对象的引用,可以在类的方法中使用它来调用当前对象的其他方法。例如:

public class MyClass {

    public void method1() {
        System.out.println("method1 is called");
    }

    public void method2() {
        System.out.println("method2 is called");
        
        // 调用当前对象的method1方法
        this.method1();
    }

    public static void main(String[] args) {
        MyClass myObject = new MyClass();
        myObject.method2();
    }
}

在上面的例子中,method2方法中使用this关键字调用了当前对象的method1方法。当main方法中调用myObject.method2()时,输出结果为:

method2 is called
method1 is called

0