在Java中创建实例变量和创建一个新对象之间的区别? [英] Difference between creating an instance variable and creating a new object in Java?

查看:258
本文介绍了在Java中创建实例变量和创建一个新对象之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解创建对象和创建变量之间的区别。例如:

  private int number; 
MyClass myObj = new MyClass();但我的观点是这两者有什么区别?








b $ b

 私人MusicPlayer播放器; 
player = new MusicPlayer();

MusicPlayer 是一个类,

$

 私人MusicPlayer播放器; 


您可以创建 MusicPlayer 类(但它不创建对象),而不初始化它。因此,您不能使用此变量,因为它不指向任何位置(它为null)。



例如,使用 code> class:

  

可表示如下:








  player = new MusicPlayer(); 

在此处,您分配 MusicPlayer ,并将它存储在 player 引用中,以便可以使用它上面的所有函数。



例如,使用 Point 类, x y coordinates:

  Point originOne = new Point(23,94); 

可表示如下:








这两行的组合等效于:

  private MusicPlayer player = new MusicPlayer 


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?

解决方案

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();

这篇关于在Java中创建实例变量和创建一个新对象之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆