2021年3月5日星期五

Why calling class function from a thread works in Java?

So I got this weird scenario that works fine but doesn't make any sense as to why it works. From my experience in C++, I'm very sure that this will not work at all and will throw an error during compilation.

public class Practice {        private void testFunction() {          System.out.println("working fine");          System.out.println("testFunc: " + this);      }        public void start() {          System.out.println("start: " + this);            new Thread(new Runnable() {              @Override              public void run() {                  System.out.println("run: " + this);                  testFunction();              }          }).start();      }  }    // Inside main  Practice practice = new Practice();  practice.start()  

Output

start: com.company.Practice@5e2de80c  run: com.company.Practice$1@6720b744  working fine  testFunc: com.company.Practice@5e2de80c  

WHY!? why did this work? How am I able to call testFunction() from a Runnable? Shouldn't I create a new instance and then call that function like Practice p = new Practice(); p.testFunction()? How does Java know that testFunction() is part of Practice class and not Runnable?

And also, how come the value of this in testFunction() is same as start()? Shouldn't it be same as run()?

https://stackoverflow.com/questions/66501906/why-calling-class-function-from-a-thread-works-in-java March 06, 2021 at 10:52AM

没有评论:

发表评论