How do I reference instances using an instance?

北慕城南 提交于 2019-12-04 05:09:33

问题


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.


回答1:


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...;


来源:https://stackoverflow.com/questions/47898225/how-do-i-reference-instances-using-an-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!