简体   繁体   English

为什么有时不必在Java中声明“新”对象?

[英]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.

相关问题 要列出的对象 - >为什么我要创建一个新对象? - Object to list -> why do I have to create a new object? 如何在 Java 中将对象声明为字段? - How do I declare an object as field in Java? 在Java中,为什么在创建新对象时有时将父类放在左侧? - In Java, why is the parent class sometimes on the left when creating a new object? 为什么我不能在新的Java 1.8中创建存根? 那么,对于没有存根的远程对象,我该怎么办? - Why am I not able to create stub in new Java 1.8? Then what should I have to do for lookup of remote object without stub? 为什么我们必须将方法声明为java中递归调用的静态方法? - Why do we have to declare method as static for recursive call in java? JAVA:为什么我需要在此函数中创建一个新的列表对象? - JAVA: Why do I need to create a new list object in this function? 为什么我有时必须使用受保护的有时不能使用? - Why I have to use sometimes protected and sometimes not? Java List Collections: Why does get(new Integer(i)) work and not when I declare an integer object first and then pass it through - Java List Collections: Why does get(new Integer(i)) work and not when I declare an integer object first and then pass it through 如果要在新线程中执行某些操作,为什么必须将最终对象发送到参数列表? - Why do I have to send the final object to the arguments list if I want to do something in a new thread? 为什么我不能在 Java 的本地类中声明对象? - Why can't I declare object in my local class in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM