gpt4 book ai didi

java - 使用 'this.methodName' 调用或仅使用 'methodName' 调用类的私有(private)方法之间的区别

转载 作者:行者123 更新时间:2023-11-29 03:31:37 24 4
gpt4 key购买 nike

我见过很多实现,其中一个类 (C1) 和这个类中的一个私有(private)方法 (M1)。我已经看到使用 this.M1 或从此类的其他方法中简单地使用 M1 来使用此方法 M1

public class C1{
private void M1(){
// do something...
}

public void M2(){
this.M1();
//OR calling as
M1();
}

private void M3(){
this.M1();
//OR calling as
M1();
}
}

什么是正确的方法?

有什么区别?


编辑

这与“当多个线程尝试访问同一方法时?”有什么关系?

public class SingletonClass {

private static SingletonClass singletonClass= new SingletonClass("apple");

private String a;

private SingletonClass(String input) {
this.a = input;
}

public static SingletonClass getInstance(){
System.out.println("ha ha "+ singletonClass.a);
return singletonClass;
}

public void m2(){
System.out.println("Here");
this.m1();
}

private void m1(){
System.out.println("here");
}
}

public class Main {

public static void main(String[] args) {
SingletonClass.getInstance().m2();
}

}

最佳答案

这是一种特殊的编码风格。在这种特殊情况下,this 是多余的,因为它是隐含的。我在发现它时使用它来提高可读性。通常你会使用 this 来解决由同名的实例变量和局部变量引起的歧义,其中局部变量隐藏实例变量:

public class C1{
private int x ;
private void M1(int x){
this.x = x;
}
}

关于java - 使用 'this.methodName' 调用或仅使用 'methodName' 调用类的私有(private)方法之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17895829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com