1

I'm trying to minimize how much I create an instance, as I am not particularly skilled in Java. Currently I have a set of instances of other classes in my Main, a quick example...

public final class ClassName extends JavaPlugin {

    AntiSwear antiSwear = new AntiSwear();
    Spam spam = new Spam();

    @Override
    public void onEnable() {
        // Plugin startup logic
    }

    @Override
    public void onDisable() {
        // Plugin shutdown logic
    }
}

And instead of making more and more instances, I just want to make an instance of the main class, ClassName className = new ClassName(); and run something like className.spam...

Basically to put my gibberish into English: I just want to see how to reference instances using an instance.

vinS
  • 1,417
  • 5
  • 24
  • 37
VeeAyeInIn
  • 193
  • 1
  • 12

1 Answers1

3

There are a few ways to go about this. The first way is to use the public access modifier:

public AntiSwear antiSwear = new AntiSwear();
public Spam spam = new Spam();

This makes the instances accessible from an instance of ClassName, for example:

ClassName className = new ClassName();
className.spam...;
className.antiSwear...;

The second method involves getters and setters, which provide a method that can be invoked by any class that contains an instance and has access, or by a subclass:

AntiSwear antiSwear = new AntiSwear();
Spam spam = new Spam();

public AntiSwear getAnitSwear(){
    return this.antiSwear;
}
public Spam getAnitSwear(){
    return this.spam;
}

Now you can invoke the getter accordingly:

ClassName className = new ClassName();
className.getSpam()...;
className.getAntiSwear()...;

The third method involves the static access modifier:

public static AntiSwear antiSwear = new AntiSwear();
public static Spam spam = new Spam();

This makes the instances accessible from every external class, even those that do not contain an instance. This is because:

static members belong to the class instead of a specific instance.

It means that only one instance of a static field exists even if you create a million instances of the class or you don't create any. It will be shared by all instances.

For example:

//Notice that I am not creating an instance, I am only using the class name
ClassName.spam...;
ClassName.antiSwear...;
Cardinal System
  • 2,749
  • 3
  • 21
  • 42
  • Notably, for Minecraft mods, the only thing that really needs to be static is a reference to the main mod class instance itself. Forge does this pretty much *for* you (I don't know about Bukkit, etc), so you end up with, e.g., `ClassName.classNameInstance.spam` as the main mod class is essentially a [Singleton](https://en.wikipedia.org/wiki/Singleton_pattern). – Draco18s no longer trusts SE Dec 21 '17 at 04:11