如何使用实例引用实例? [英] How do I reference instances using an instance?
问题描述
由于我对Java没有特别的了解,所以我正在尝试最小化创建实例的数量.目前,我的Main中有一组其他类的实例,一个简单的示例...
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
}
}
而不是创建越来越多的实例,我只想创建主类ClassName className = new ClassName();
的实例并运行类似className.spam...
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.
推荐答案
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();
这使得可以从ClassName
的实例访问实例,例如:
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;
}
现在您可以相应地调用getter了:
Now you can invoke the getter accordingly:
ClassName className = new ClassName();
className.getSpam()...;
className.getAntiSwear()...;
第三种方法涉及 static
访问修饰符:
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
成员属于该类,而不是 具体实例.
static
members belong to the class instead of a specific instance.
这意味着 static
字段仅一个实例
存在,即使您创建了该实例的一百万个实例
类,否则您将不会创建任何类.它将被所有实例共享.
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.
例如:
//Notice that I am not creating an instance, I am only using the class name
ClassName.spam...;
ClassName.antiSwear...;
这篇关于如何使用实例引用实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!