Object vs Reference in Java

前端 未结 8 2078
梦如初夏
梦如初夏 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

    Sometimes you'll hear people say "Design an method that takes an object as a parameter and..."

    If you're new to programming, and especially with Java, such statements can lead to some confusion. These people are using the word "object" to refer to an instance of a class in very general OOP terms, not necessarily Java specific.

    When we're talking specifics about Java and the code you have there, it is a reference to an instance of MyClass, which is NULL.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题