java类怎么调用自己的方法

28次阅读
没有评论

共计 456 个字符,预计需要花费 2 分钟才能阅读完成。

在 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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-05-08发表,共计456字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)