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

后端 未结 6 1424
生来不讨喜
生来不讨喜 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 21:53

    private MusicPlayer player; This assigns in memory a 4 byte space (or perhaps more, on 64 bit machines) that COULD eventually point towards an object in the heap. That object wasn't created, so it doesn't exist, so the player variable points to the null value.... but that takes 4 bytes to do. This is essentially like reserving the name "Stinky" for a dog that you plan to own, but you don't yet have.

    player = new MusicPlayer(); this thing creates in the heap as much space as it is needed for an object of type MusicPlayer to exist. That space equals a header of dunnow how many bytes, to indicate the class of that object and additional memory needed to store its declared instance variables (meaning additional 4 - or more - bytes for every object reference declared as a instance variable (if null), and additional bytes for the primary data types. This is essentially like making sure you HAVE a dog called "Stinky".

提交回复
热议问题