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

后端 未结 6 1436
生来不讨喜
生来不讨喜 2020-12-10 21:36

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

private int number;
MyClass myObj = new MyClass();
6条回答
  •  感动是毒
    2020-12-10 22:08

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

提交回复
热议问题