Use “this” and method (in Java)
What about using the "this" method in Java? Are there selective or mandatory situations?
The only thing I encountered was calling the method in the class in the class. But it is optional This is a stupid example, just to show what I mean:
public class Test { String s; private String hey() { return s; } public String getS(){ String sm = this.hey(); // here I Could just write hey(); without this return sm; } }
Solution
Three obvious situations you need:
>Call another constructor in the same class as the first part of the constructor > distinguish between local variables and instance variables (whether in constructors or other methods) > pass a reference to the current object to another method
Here are three examples:
public class Test { int x; public Test(int x) { this.x = x; } public test() { this(10); } public void foo() { Helper.doSomethingWith(this); } public void setX(int x) { this.x = x; } }
I believe there are some strange situations. Using inner classes, you need super this. x. But they should be avoided, IMO
The above is all the contents of using "this" and methods (in Java) collected and sorted by programming house for you. I hope this article can help you solve the program development problems encountered in using "this" and methods (in Java).
If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.