Java 使用/不使用此关键字调用方法有什么区别
我有个问题。 请不要把它标为重复题,把问题重读一遍。我找不到这个特定情况/条件的答案,如果你觉得它有一个特定的答案,那么只标记重复。将其标记为重复会使我的问题仍然是一个没有答案的问题 使用/不使用此作为关键字调用方法有什么区别。哪一个更好? 这个问题特别适用于一个班级 请看下面的示例代码以完全理解问题Java 使用/不使用此关键字调用方法有什么区别,java,oop,this,Java,Oop,This,我有个问题。 请不要把它标为重复题,把问题重读一遍。我找不到这个特定情况/条件的答案,如果你觉得它有一个特定的答案,那么只标记重复。将其标记为重复会使我的问题仍然是一个没有答案的问题 使用/不使用此作为关键字调用方法有什么区别。哪一个更好? 这个问题特别适用于一个班级 请看下面的示例代码以完全理解问题 public class ThisSample { public static void main(String[] args) { ThisSample sample = new Thi
public class ThisSample {
public static void main(String[] args) {
ThisSample sample = new ThisSample();
sample.methodOne();
}
public void methodOne() {
System.out.println("Method 1 called");
this.methodTwo(); //Line 1
methodTwo(); // Line 2
}
public void methodTwo() {
System.out.println("Method 2 called");
}
}
代码中的第1行和第2行有什么不同的优点/缺点/含义
谢谢和问候,
Yadvendra“此”任务是区分对象属性和方法参数。在所展示的代码中,使用此选项没有任何作用。但是,最常见的用法如下所示:
public class Service {
private ServiceA serviceA;
private ServiceB serviceB;
// Here 'this' is used to make sure that class instance
// properties are filled with constructor parameters
public Service(ServiceA serviceA, ServiceB serviceB) {
this.serviceA = serviceA;
this.serviceB = serviceB;
}
}
这用于指定您正在谈论来自类ThisSample的当前实例的方法Method2
如果您有另一个名为AnotherSample的类:
您可以使用methodThree方法,方法如下调用另一个Sample.methodThree
总而言之:这只是指定您正在使用当前正在编码的类的实例。在您给出的示例中,差异没有什么。让我稍微修改一下您的代码:
public class ThisSample {
int variable;
public static void main(String[] args) {
ThisSample sample = new ThisSample();
sample.methodOne(3);
sample.methodTwo(5);
}
public void methodOne(int variable) {
this.variable = variable;
System.out.println("variable is: " + this.variable);
}
public void methodTwo(int variable) {
variable = variable;
System.out.println("variable is: " + this.variable);
}
}
这里,对于方法2,必须使用this.variable来设置实例变量中的值。否则,两种方法都将在此处打印3。第二种方法也是打印3,因为在方法1中设置了3
现在在方法2中,在
变量=变量
这两个变量都是方法2的参数。但是当你写作的时候
this.variable=变量
可以看出,左边的部分是这个对象的实例变量,右边的部分被分配给这个对象的实例变量
编辑:
如果你想知道哪个更受欢迎,那么也可以查看此链接。在这里使用这个被认为是多余的。链接是:
这里还说,如果我真的需要重构代码来推导实例变量,我应该重构代码。在本例中:无。这只是指向您的类的当前实例,该方法runs@Stultuske这个例子只是为了澄清这个问题。我的问题是关于概念和内部工作。首先,这些方法都不是静态的。打印不正确。@Yadvendra始终确保您显示的代码代表您所询问的代码。如果你的代码只是为了澄清问题,但基于它得出的结论不适用于你的代码:它真的没有澄清任何事情。@Yadvendra:在你发布的示例中,没有功能上的区别或优势。不,你不能像另一个示例那样调用该方法。methodThree;因为它不是静态的。你的陈述是错误的。这引用了当前实例,而不是一般地引用类。@托马斯你是对的,我犯了一个粗心的错误。你可以用它来调用静态方法。试试看!!事实上,使用此.methodName没有实际用途。。。这就是问题所在。这与我刚才说的并不矛盾:-谢谢你的回答。我知道变量的概念。我只是想知道哪个方法应该优先调用其他方法。不管有没有。哦,我也按照你的期望编辑了我的答案。谢谢@亚德文德拉
public class ThisSample {
int variable;
public static void main(String[] args) {
ThisSample sample = new ThisSample();
sample.methodOne(3);
sample.methodTwo(5);
}
public void methodOne(int variable) {
this.variable = variable;
System.out.println("variable is: " + this.variable);
}
public void methodTwo(int variable) {
variable = variable;
System.out.println("variable is: " + this.variable);
}
}