Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between creating an instance variable and creating a new object in Java?

Tags:

java

class

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?

like image 460
Imonar Smith Avatar asked Mar 18 '26 10:03

Imonar Smith


2 Answers

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).

For example, using a Point class:

Point originOne;

can be represented like this:

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.

For example, using a Point class, with x and y coordinates:

Point originOne = new Point(23, 94);

can be represented like this:

enter image description here


The combination of the two lines is equivalent to:

private MusicPlayer player = new MusicPlayer();
like image 139
Alya'a Gamal Avatar answered Mar 21 '26 01:03

Alya'a Gamal


private MusicPlayer player;

declares an instance variable named player but does not initialize it.

player = new MusicPlayer();

assigns a value to the already-declared field.

like image 28
Matt Ball Avatar answered Mar 20 '26 23:03

Matt Ball