Object vs Reference in Java

前端 未结 8 2096
梦如初夏
梦如初夏 2020-12-03 03:41

In Java, if I declare,

MyClass obj;

Is obj called a \"reference\" or an \"object\". I am not instantiating class here.

8条回答
  •  甜味超标
    2020-12-03 04:11

    The reference is a variable that has a name and can be used to access the contents of an object. A reference can be assigned to another reference, passed to a method, or returned from a method.

    All references are the same size, no matter what their type is. An object sits on the heap and does not have a name. Therefore, you have no way to access an object except through a reference. Objects come in all different shapes and sizes and consume varying amounts of memory. An object cannot be assigned to another object, nor can an object be passed to a method or returned from a method. It is the object that gets garbage collected, not its reference.

提交回复
热议问题