且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java中创建实例变量和创建一个新对象之间的区别?

更新时间:2023-11-30 13:59:28

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:


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:


The combination of the two lines is equivalent to:

private MusicPlayer player = new MusicPlayer();