0

This main class is initialized by the Bukkit framework and cannot be initialized again.

public class Demo extends JavaPlugin {
    public void onEnable() {

    }
}

How do I access its unique instance from other classes?

public class CoolDown extends BukkitRunnable {
    public CoolDown(Demo mainClass, int time) {

    }
    public void run() {

    }
}
Unihedron
  • 10,902
  • 13
  • 62
  • 72

2 Answers2

3

If you want to use the OOP way: In your CoolDown class, have a field with the type of Demo (or your JavaPlugin-extending class). You may also create any other fields you will pass in the constructor here.

private final Demo plugin;
private int time;

Then instantiate the fields using the CoolDown's constructor

public CoolDown(Demo plugin, int time) {
    this.plugin = plugin;
    this.time = time;
}

Now you can use the plugin field for your needs. Example:

public void run() {
    plugin.fooBar();
}

If you want to use the Static Programming way (not recommended, you are in a OOP language being Java!): In your Demo class, have a public, static field of type Demo, without any value (this is after the class decleration, by the way).

public static Demo instance;

In your plugin's enable method (I suggest to put this at the very first line of the method invokation):

instance = this;

Then you can use, in your CoolDown's run() method invokation:

Demo.instance.fooBar();

Once again, I do not suggest using static programming in Java. It's a lazy and bad practice in general.

Here is a full example, in your case, in OOP programming:

public class Demo extends JavaPlugin {
    public void onEnable() {
        Bukkit.getScheduler.scheduleMyEpicCooldown(new CoolDown(this, time), time);
    }
}


public class CoolDown extends BukkitRunnable {
    private final Demo plugin;
    private int time;

    public CoolDown(Demo plugin, int time) {
        this.plugin = plugin;
        this.time = time;
    } 

    public void run() {
        plugin.fooBar();
    }
}
Momo
  • 3,542
  • 4
  • 21
  • 34
2

You have to re-invent the Singleton Pattern.

public class Demo extends JavaPlugin {
    private static Demo instance;
    public Demo() {
        instance = this;
    }
    public static Demo getInstance() {
        return instance;
    }
    @Override
    public void onEnable() {

    }
}

To access:

public class Cooldown extends BukkitRunnable {
    @Override
    public void run() {
        Plugin main = Demo.getInstance();
        main.getServer().broadcastMessage("No need to have the main instance as member variable on each class.");
    }
}
spongebob
  • 8,370
  • 15
  • 50
  • 83
  • 1
    Noteworthy statement is that when a class requires the instance, it can simply invoke the public `Demo.getInstance()` method. This global access point removes the need for reinitialization. – Unihedron Aug 08 '15 at 13:19
  • @Unihedron Added in the answer. – spongebob Aug 08 '15 at 13:29