How do I reference instances using an instance?

非 Y 不嫁゛ 提交于 2019-12-02 04:50:12

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