THIS usage

xiaoxiao2021-03-06  100

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. Instead of constructor, such as this ().

The above two points will not be described again.

However, I think this is still a phenomenon that everyone may not notice:

Maybe sometimes you will find the following phenomenon:

Public Class Test Implements Runnable {Thread Thread1; 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 (); }

At |, you may be strange: Why can you call yourself when you haven't created it?

In order to explain the phenomenon above, the inheritance of the constructor must be explained first.

If there are two classes into inheritance, then

If the default constructor does not explicitly declares, then the sub-constructor must first call its parent class default constructor (in fact, I think the first constructor is more appropriate, that is, the constructor without income, then call yourself 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).

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

New Post(0)