¿Diferencia entre crear una variable de instancia y crear un nuevo objeto en Java?

I understand the difference between creating an object and creating a variable. For example:

private int number;
MyClass myObj = new MyClass();

But my point here is what's the difference between these two?

private MusicPlayer player;
player = new MusicPlayer();

MusicPlayer is a class, but what exactly are we doing here?

preguntado el 05 de mayo de 13 a las 15:05

La primera de ellas es declaración, este último es inicialización. -

6 Respuestas

private MusicPlayer player;

Here you create a reference variable of MusicPlayer class (but it does not create an object) without initializing it. So you cannot use this variable because it just doesn't point to anywhere (it is null).

Por ejemplo, usando un Point clase:

Point originOne;

se puede representar así:

enter image description here


player = new MusicPlayer();

Here, you allocate an object of type MusicPlayer, and you store it in the player reference, so that you can use all the functions on it.

Por ejemplo, usando un Point clase, con x y y coordenadas:

Point originOne = new Point(23, 94);

se puede representar así:

enter image description here


The combination of the two lines is equivalent to:

private MusicPlayer player = new MusicPlayer();

respondido 26 nov., 15:11

Wrong - the first statement does no "create object from MusicPlayer class". It creates a variable that can reference such objects. - Andy Tomas

Still not quite right. In the first sentence, there is no "this object." In the second sentence, you're creating the object, not just initializing it. And the second statement is not equivalent to the third. - Andy Tomas

no, i mean the initialization with the declaration is equivalent to the third ) - Alya'a Gamal

private MusicPlayer player;

declara una variable de instancia llamado player pero no inicializar él.

player = new MusicPlayer();

assigns a value to the already-declared field.

contestado el 05 de mayo de 13 a las 15:05

private MusicPlayer player;

It's a declaration, This means to make a new reference variable of MusicPlayer, just a reference, and no instance will be created. You cannot use it because it points to null.

player  = new MusicPlayer();

MusicPlayer() calls the MusicPlayer constructor, new create a instance of MusicPlayer, = assigns this instance to the reference player.

contestado el 05 de mayo de 13 a las 16:05

A class is a type. Java is a strongly typed language, so most of the time it needs to know the types of the things it is dealing with.

A reference variable simply holds a reference to an object. Because Java is strongly typed, it always wants to know the type of the reference that a variable is holding (i.e., since a class is a type, it wants to know the class of the object that a variable's reference points to).

whatEver object1 = new whatEver();
  1. declares a reference variable (object1) and that its type is whatever
  2. creates a new() object of type whatever
  3. assigns the reference for the new whatever object to the reference variable object 1
  4. the assignment is valid because the type of the object and the type of the variable agree

El siguiente es...

private MusicPlayer player;
player  = new MusicPlayer();

The above accomplishes a similar result, but in multiple steps. The 1st line only establishes that the variable player will hold a reference to an object of type MusicPlayer. Java always wants to know the types of things before they are used.

The second line creates a new() object of type MusicPlayer and assigns its reference to variable player. The assignment is, again, valid because the type of the object and the type of the reference variable agree.

contestado el 05 de mayo de 13 a las 15:05

private MusicPlayer player; This assigns in memory a 4 byte space (or perhaps more, on 64 bit machines) that COULD eventually point towards an object in the heap. That object wasn't created, so it doesn't exist, so the player variable apunta a la null value.... but that takes 4 bytes to do. This is essentially like reserving the name "Stinky" for a dog that you plan to own, but you don't yet have.

player = new MusicPlayer(); this thing creates in the heap as much space as it is needed for an object of type MusicPlayer to exist. That space equals a header of dunnow how many bytes, to indicate the class of that object and additional memory needed to store its declared instance variables (meaning additional 4 - or more - bytes for every object reference declared as a instance variable (if null), and additional bytes for the primary data types. This is essentially like making sure you HAVE a dog called "Stinky".

contestado el 05 de mayo de 13 a las 15:05

This question's answer is in https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html.
I will use the example a imaginary Peces class. When using the below method,

Fish tuna;

the statement notifies the compiler that you will use name to refer to data whose contents is of type tipo. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. If you declare a variable like this, its value will be undetermined until an object is actually created and assigned to it.

When you write the following statement,

Fish tuna = new Fish();

the new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

The new operator returns a reference to the object it created. This reference is usually assigned to the variable of the appropriate type.

Therefore when you say,

Fish tuna = new Fish();

you are creating an variable of type Fish which can hold an object of type Fish and using the new operator you are creating an object of that type and returning an reference to it.

respondido 26 nov., 15:11

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.