How do I reference instances using an instance?

后端 未结 1 506
被撕碎了的回忆
被撕碎了的回忆 2021-01-25 19:51

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

相关标签:
1条回答
  • 2021-01-25 20:45

    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...;
    
    0 讨论(0)
提交回复
热议问题