morTie morTie - 1 month ago 7
Java Question

Calling a method of an object from another object inside it

I'm new to java and I want to create a multi-threaded application as I'm gonna describe:

  • There are two main objects a job and a jobRunner.

  • jobRunner would be created at the beginning and it would fetch a list of strings describing jobs, then it would create a List of job objects.

  • each job object has a method to run a series of actions in a separate thread. Using that, the jobRunner would run a bunch of jobs toghether on separate threads

  • jobRunner has also a method to finilize and report back the job status and so each finished job needs to call back that method in it's parent object

My question is about the final step. How can an object inside another one call a method of it's preceding object? Or is it possible to pass an address of the jobRunner object to the job objects so that they would call the object by that address? Thank you for enlightening me :)


Two options. 1) Use a callback (Cleaner approach) 2) Pass in a reference JobRunner as a parameter to Job (quick approach)

Callback example Declare an interface and define a method to be called at various points in the jobs lifecycle, e.g. void finished()

JobRunner can implement the interface, and passes this to Job. When job is done it can invoke the callback method.

Simple Callback example

public interface JobUpdate {
  void jobCompleted();

public JobRunner implements JobUpdate {
   public void jobCompleted() {
     // Our implemented callback method, called from Job

public Job() {
  private JobUpdate update;

  public Job(JobUpdate update) {
    this.update = update;

  public void runJob() {
    // at correct point, invoke the appropriate callback method