Jump to content

this keyword in constructor


Recommended Posts

Posted

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);   }

Posted (edited)
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

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