Home > Software design >  printing an instance in run method
printing an instance in run method

Time:01-01

My question is that we have not created an object from class A in the following code yet, but how does it return a value in the run method when we print this? When was this object created?

class A implements Runnable {
@Override
public void run() {
    System.out.println(this); // prints org.ISOFT.A@78a56018

 } 
}

CodePudding user response:

You don't create an instance of A with that code, and in fact, as written, by itself that code will compile but will print nothing and will do nothing since it has no main method, no starting point and no thread creation.

You will only see something when/where you have new A(), and then call its run() method, either directly, or much more commonly, indirectly by passing it into a thread, such as with

public class Foo {
    public static void main(String[] args) {
        new Thread(new A()).start();
    }
}

Here, the Thread object will call A's run() method from within Thread's start() method.

Or alternatively,

ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(new A());
executorService.shutdown();

Where again, you create a thread, pass in A, and the thread calls A's run() method indirectly when it starts.

So, to answer your direct questions:

My question is that we have not created an object from class A in the following code yet,

That is correct

but how does it return a value in the run method when we print this?

It never actually "returns a value" ever since it is has been declared to be a void method, one which returns nothing. And the code, as posted, doesn't print anything (which is likely what you meant by "return a value") unless an A object is instantiated and is passed into a thread object which is then started, as shown above.

When was this object created?

Nowhere in the code that you've posted.

  • Related