[英]Why do I not have to declare a “new” object sometimes in Java?
Apologies for what is probably an easy question. 抱歉,这可能是一个简单的问题。 I cannot find anything straight forward to answer this one. 我找不到任何直接答案。 In the following code, why am I not required to create a "new" object? 在下面的代码中,为什么不需要创建“新”对象? What exactly am I assigning sequencer to? 我到底要将音序器分配给什么?
import javax.sound.midi.*;
public class MusicTest1 {
public void play() {
Sequencer sequencer = MidiSystem.getSequencer();
System.out.println("We got a sequencer");
} // close play
public static void main(String[] args) {
MusicTest1 mt = new MusicTest1();
mt.play();
}
}
If you are referring to Sequencer sequencer = MidiSystem.getSequencer();
如果您指的是定Sequencer sequencer = MidiSystem.getSequencer();
, you are calling a static method of the class MidiSystem
that returns an instance of Sequencer
. ,您正在调用MidiSystem
类的静态方法,该方法返回Sequencer
的实例。 The static method does the new Sequencer()
for you. 静态方法为您执行new Sequencer()
。
The function getSequencer
makes a new object and returns it. 函数getSequencer
创建一个新对象并返回它。 It probably returns the same object if it has already created one. 如果已经创建了一个对象,它可能会返回相同的对象。 This is called the singleton pattern. 这称为单例模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.