[英]Why isn't the class MediaPlayer instantiated using new keyword
I am looking at some tutorials for Android development and I saw the case below 我正在查看一些有关Android开发的教程,并且看到了以下情况
MediaPlayer mp = MediaPlayer.create(this, R.id.song)
My question is the following: Why isn't there a "new" keyword involved when creating a new MediaPlayer object? 我的问题如下:创建新的MediaPlayer对象时,为什么没有涉及“ new”关键字? I thought that new has to be used anytime you create a instance of class
我认为在创建类的实例时必须使用new
So what if I do 那我该怎么办
MediaPlayer mp = new MediaPlayer();
mp.create(this, R.id.song);
is this wrong? 这是错的吗?
My question is the following: Why isn't there a "new" keyword involved when creating a new MediaPlayer object?
我的问题如下:创建新的MediaPlayer对象时,为什么没有涉及“ new”关键字?
Well you're calling a static method which will (presumably) create a new instance. 好吧,您正在调用一个静态方法,该方法将(大概)创建一个新实例。
Maybe that method calls the constructor directly - or maybe it creates an instance of some subclass. 也许那个方法直接调用了构造函数-或者也许它创建了一个子类的实例。 Or maybe it returns a reference to an existing instance instead.
或者,也许它返回对现有实例的引用。
That's the nice thing about factory methods - they get to hide their implementation details :) 那是工厂方法的好处-它们可以隐藏其实现细节:)
This is a "factory"-function. 这是“工厂”功能。 Internally it calls
new MediaPlayer()
, you just do not see it from outside of the class. 在内部它调用
new MediaPlayer()
,只是您从类外部看不到它。
You are actually allowed to call new on a MediaPlayer. 实际上,您被允许在MediaPlayer上调用new 。
The following is taken from http://developer.android.com/reference/android/media/MediaPlayer.html 以下内容摘自http://developer.android.com/reference/android/media/MediaPlayer.html
When a MediaPlayer object is just created using new or after reset() is called, it is in the Idle state [...] Furthermore, the MediaPlayer objects created using new is in the Idle state, while those created with one of the overloaded convenient create methods are NOT in the Idle state.
当刚使用new创建MediaPlayer对象或在调用reset()之后,它处于空闲状态[...]此外,使用new创建的MediaPlayer对象处于空闲状态,而使用重载之一创建的对象方便的创建方法不在空闲状态。 In fact, the objects are in the Prepared state if the creation using create method is successful.
实际上,如果使用create方法创建成功,则对象将处于Prepared状态。
Basically using new vs the static method just changes what state your MediaPlayer is in. If you new one, then you'll have to initialize it with setDataSource() and prepare it with onPrepare(). 基本上使用new与static方法只会改变MediaPlayer的状态。如果是新方法,则必须使用setDataSource()对其进行初始化,并使用onPrepare()对其进行准备。 Where as your all ready to go with the static helper.
当您准备好与静态助手一起使用时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.