Talking about the use of this in Java

xiaoxiao2021-03-06  55

Talk about the use of this in Java 1. This is the current object yourself. When you want to use the object's own variables or functions to use this object, you should add this reference. As in this example: public class a {string s = "hello"; public a (string s) {system.out.println ("s =" s); system.out.println ("1 -> this. S = " this.s); this.s = s; system.out.println (" 2 -> this.s = " this.s);} public static void main (String [] args) {new a ("HelloWorld!");}} Run: S = HelloWorld! 1 -> this.s = hello2 -> this.s = helloworld! In this example, the constructor A, the parameter S and the variable S of the class A At the same name, if the S can operate directly, the parameter S is operated. To operate the variable S of class A, you should use this. The first line of the running result is to print the parameter S directly; the back two rows are the print results before and after the variable S of the object A. 2. Pass the THIS as a parameter. When you want to pass your own parameters to other objects, you can use this. Such as: public class a {public a () {new b (this) .print ();} public void print () {system.out.println ("Hello from A!");}} Public class b {a a Public b (a) {this.a = a;} public void print () {a.print (); system.out.println ("Hello from B!");}} Run Results: Hello from A! Hello From B! In this example, in the constructor of the object A, the object A is passed to the constructor of the object B as a parameter with New B (this). 3. Pay attention to the this in the anonymous class and the inner class. Sometimes we use some internal classes and anonymous classes. When this this this this this this this is anonymous or the internal class itself when using this in anonymous class. At this time, if we want to use the external classes and variables, you should add the class name of the external class. Such as follows: public class a {int I = 1; public a () {thread thread = new thread () {public void Run () {for (;;) {a.this.Run (); try {sleep (1000);} catch (interruptedException IE {}}}}; thread.start ();} public void run () {system.out.println ("i =" i); i ;} public static void main (String [] args) THROWS Exception {new a ();}} In this example, thread is an anonymous class, in its definition, its Run function is used in the RUN function of the external class. At this time, because the function is the same name, it will not be called directly. There are two ways at this time that one is to change the external Run function, but this approach is not advisable for a development to the middle.

转载请注明原文地址:https://www.9cbs.com/read-117122.html

New Post(0)