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

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

    This question's answer is in https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html.
    I will use the example a imaginary Fish class. When using the below method,

    Fish tuna;
    

    the statement notifies the compiler that you will use name to refer to data whose contents is of type type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. If you declare a variable like this, its value will be undetermined until an object is actually created and assigned to it.

    When you write the following statement,

    Fish tuna = new Fish();
    

    the new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

    The new operator returns a reference to the object it created. This reference is usually assigned to the variable of the appropriate type.

    Therefore when you say,

    Fish tuna = new Fish();
    

    you are creating an variable of type Fish which can hold an object of type Fish and using the new operator you are creating an object of that type and returning an reference to it.

提交回复
热议问题