1.this is the current object itself. When a class object to be clear that the use of their own variable or function should add this reference. Such as the following example: publicclassA (Strings = 'Hello'; publicA (Strings) (System.out.println ('s =' + s); Sys ...
1.this is currently the object itself.
When a class object to be clear that the use of their own variable or function should add this reference. Such as the following example:
publicclassA (
Strings = "Hello";
publicA (Strings) (
System.out.println ("s =" + s);
System.out.println ("1 -> this.s =" + this.s);
this.s = s;
System.out.println ("2 -> this.s =" + this.s);
)
publicstaticvoidmain (String [] args) (
newA ("HelloWorld!");
)
)
Run Results:
s = HelloWorld!
1 -> this.s = Hello
2 -> this.s = HelloWorld!
In this example, the constructor A, the parameter s and the class A variable s the same name, this time directly to the s to operate if it is to operate on the parameters s. To the class A variable s should be used to operate on this for reference. The results of the first line to run directly on the parameter s is to print the results; the back two rows are the object A variable s to print the results before and after operation.
2. To this as a parameter
When you make your object as a parameter passed to the other, they can use this. Such as:
publicclassA (
publicA () (
newB (this). print ();
)
publicvoidprint () (
System.out.println ("HellofromA!");
)
)
publicclassB (
Aa;
publicB (Aa) (
this.a = a;
)
publicvoidprint () (
a.print ();
System.out.println ("HellofromB!");
)
)
Run Results:
HellofromA!
HellofromB!
In this example, the constructor of the object A with newB (this) to the object A itself as a parameter to the constructor of the object B.
3. Note that anonymous classes and inner classes in the middle of this.
Sometimes, we will use some internal classes and anonymous classes. When using this anonymous class, this means that this is anonymous class or inner class itself. Then if we are to use an external class methods and variables, then the class should be added outside the class name. Such as the following example:
publicclassA (
inti = 1;
publicA () (
Threadthread = newThread () (
publicvoidrun () (
for (;;){
A.this.run ();
try (
sleep (1000);
) Catch (InterruptedExceptionie) (
)
)
)
);
thread.start ();
)
publicvoidrun () (
System.out.println ("i =" + i);
i + +;
)
publicstaticvoidmain (String [] args) throwsException (
newA ();
)
)
In the above example, thread is anonymous class object, in his definition, he's run the function in use of external class run function. Then the same name as the function, called directly on to die. Then there are two ways, one is to run outside for a function name, but this approach to the way for a development application is not desirable. Then able to approach this case the class name with an external class with this reference to show to call an external class method run.
No comments:
Post a Comment