0

I Need some clarification how below code work in java.

I have interface call TaskDataProvider.

    public interface TaskDataProvider {
        String getTaskName();
    }

Also there is class TaskExecutor which need TaskDataProvider

    public class TaskExecutor {
       private TaskDataProvider taskDataProvider;

       public TaskExecutor(TaskDataProvider taskDataProvider) {
           this.taskDataProvider = taskDataProvider;
       }

       public void execute() {
           System.out.println(taskDataProvider.getTaskName());
       }
    }

FirstTask which crate TaskDataProvider and it contain TaskExecutor which create inside FirstTask Interface.

    public class FirstTask implements TaskDataProvider {

        private TaskExecutor taskExecutor;

        public FirstTask() {
            this.taskExecutor = new TaskExecutor(this);
        }

        public TaskExecutor getTaskExecutor() {
            return taskExecutor;
        }

        @Override
        public String getTaskName() {
            return "First Task";
        }
    }

Now When we create FirstTask, we refer "this" to refer same FirstTask instance when creating TaskExecutor. But when the time use "this" its not fully completed FirstTask instance creation. ("this" refer inside constructor). I feel this flow as we are referring incomplete instance via "this"

But this is working fine. I need to know how this work fine. and it cannot be exception on any time in this process.

So please help me to understand this. Thanks.

Chamly Idunil
  • 1,848
  • 1
  • 18
  • 33
  • 1
    the constructor is used to set a state to the instance, meaning to set a value to the instance variables, it's quite logical it already has access to them – Stultuske Oct 12 '18 at 06:11
  • 2
    This is exactly the [leaking `this` in a ctor anti-pattern](https://stackoverflow.com/questions/3921616/leaking-this-in-constructor-warning) - so you are absolutely right - you're leaking the class before it has been fully constructed and none of the guarantees that Java provides around constructed objects yet hold - it gets worse if `FirstTask ` has a subclass... – Boris the Spider Oct 12 '18 at 06:23
  • I doubt you need to have `TaskExecutor` as an instance member of your `FirstTask`. Very likely, any context in which you are calling `getTaskExecutor()`, you will already have a reference to that object. And if not, I would redesign it as such. – Joe Coder Oct 12 '18 at 06:39

1 Answers1

2

An object is created, before the constructor is called. Otherwise, the constructor could not access it via this.

You can find a quite detailed analysis of class and object instantiation here: Java order of Initialization and Instantiation

Ridcully
  • 23,362
  • 7
  • 71
  • 86