JavaSound API中getSequencer方法为何能返回Sequencer接口实例?
MidiSystem.getSequencer() return an instance of the Sequencer interface? You’re absolutely right that you can’t instantiate an interface directly—but that’s not what’s happening here. The getSequencer() method isn’t creating an instance of the Sequencer interface itself. Instead, it returns an object from a concrete class that implements the Sequencer interface, leveraging Java’s polymorphism feature.
Let me break this down:
- Polymorphism in Java lets you use an interface type to reference an object from any class that implements that interface. This hides the messy details of the concrete implementation, exposing only the methods defined in the interface—making your code more flexible and easier to maintain.
- Under the hood,
MidiSystem.getSequencer()checks your system environment, picks an appropriate implementation class (likecom.sun.media.sound.SoftSequencer, a common built-in implementation), creates an instance of that class, and then upcasts it to theSequencerinterface type before returning it to you.
To make this clearer, here’s a simplified example that mirrors how MidiSystem works:
// Our "Sequencer" equivalent interface interface AudioPlayer { void play(); } // A concrete class implementing the interface class Mp3Player implements AudioPlayer { @Override public void play() { System.out.println("Playing MP3 file..."); } } // Our "MidiSystem" equivalent factory class class PlayerFactory { public static AudioPlayer getPlayer() { // Return a concrete implementation instance, upcast to the interface return new Mp3Player(); } } // Usage public class Main { public static void main(String[] args) { AudioPlayer player = PlayerFactory.getPlayer(); player.play(); // Calls Mp3Player's play() method } }
If you want to see the actual concrete class behind your Sequencer instance, you can run this quick check:
Sequencer sequencer = MidiSystem.getSequencer(); System.out.println(sequencer.getClass().getName());
This will print the fully qualified name of the real implementation class (not the interface name), confirming that you’re working with a concrete object that adheres to the Sequencer contract.
内容的提问来源于stack exchange,提问作者pc.97

