Java research: THIS is a little known

xiaoxiao2021-03-06  38

Java research: THIS is a little known

source:

9CBS Author:

QLAMPSKYFACE

It is well known that the two uses of this are very common. 1. Replace the current instance. For example this. Member variable name, this. Member method name 2. Replace the constructor, such as this (). These two points will not be described. But, I think This is also a phenomenon that everyone may not notice: may sometimes find the following phenomenon: public class test1; thread thread2; public test () {thread1 = new thread (this, "1"); // ----------------------> | thread2 = new thread (this, "2"); // ---------- ------------> |} public static void main (string args []) {test t = new test (); t.startthreads ();} public void run () {// DO Thread's Things} () {thread1.start (); thread2.start (); thread2.start ();}} You may be very strange: Why can you call yourself if you have not created? In order to explain it clearly? The above phenomenon must first be clear to the inheritance of the constructor. If there are two classes into inheritance relationships, then if the default constructor does not explicitly declare, then the sub-constructor must call its parent class default constructor (in fact I think that the first constructor is more suitable, that is, the constructor without inclusion), then calls its own constructor. Below we will follow the strange phenomena, why can I use this to replace itself without creating a subclass object? That is because the default constructor of the parent class has been called before the subclass constructor is called. The parent class is Object. You can also let Test inherit a class to see if there is a constructor of its parent class. In the above, due to the limited self-capacity, it is not discussed in depth of this topic, but the skin is to explain I hope to be able to throw the jade. Please correct it!

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

New Post(0)