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

后端 未结 6 1434
生来不讨喜
生来不讨喜 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:17

    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

    Next is...

    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.

提交回复
热议问题