Jump to content

this keyword in constructor


Jammer

Recommended Posts

So I'm trying to add a new task to an ArrayList or rather create a new task.

tasks.add(new DropTask(this));

What I don't get is what the keyword this does here. I've only seen "this" used in methods to differenciate between the local variable and the instance variable.

 

Might be worth adding that the constructor in the DropTask class looks like this: public DropTask(MethodProvider api) { super(api);   }

Link to comment
Share on other sites

13 minutes ago, Jammer said:

So I'm trying to add a new task to an ArrayList or rather create a new task.

tasks.add(new DropTask(this));

What I don't get is what the keyword this does here. I've only seen "this" used in methods to differenciate between the local variable and the instance variable.

 

Might be worth adding that the constructor in the DropTask class looks like this: public DropTask(MethodProvider api) { super(api);   }

 

Consider reading this https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Essentially all it is doing is passing a reference to the current instance (which is of type MethodProvider) as a parameter to the constructor of DropTask

 

An alternative method, instead of passing around a instance of MethodProvider to access the API, would be to just make your other classes extend MethodProvider, and then exchangeContext:

 

public class SomeScript extends Script {

    SomeOtherClass someOtherClass;
  
    @Override
    public void onStart() {
        someOtherClass = new SomeOtherClass();
        someOtherClass.exchangeContext(getBot());
    }
}

class SomeOtherClass extends MethodProvider {
  
}

 

Edited by Explv
  • Like 3
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...