Is there a formal or authoritative definition for “dereferencing” in Java?

后端 未结 2 1246
深忆病人
深忆病人 2020-12-16 11:56

Coming from a C and C++ background, I have always assumed that dereferencing in Java is the process of accessing an object via its reference.

For example, \"ref\" i

相关标签:
2条回答
  • 2020-12-16 12:16

    Although there is no official definition, the word 'dereference' is used in some of the Java error statements.

    For example, if you write following code:

    char ch = 'A';
    if (ch.isLetter()) { }
    

    You get error: char cannot be dereferenced

    So, one can say that accessing the state or behaviour of an object using its reference with the help of the . operator is dereferencing.

    0 讨论(0)
  • 2020-12-16 12:21

    Java variables are either "primitive types" or "reference types" in Oracle's terminology (well, other than the special type of null). I came to Java from a C++ background and always found it easiest to think of reference types like pointers as that makes it easiest to understand how they work (though there are important differences), however because all non-primitive variables are like that there's no concept of evaluation (no equivalent of C++'s dereferencing of pointers).

    So, in your example:

    Integer ref = new Integer(7); 
    ref = null;
    

    On the first line an object is created on the heap and ref refers to it. On the second line ref is changed to refer to null. There are no more references to the object on the heap so it will have become eligible for garbage collection, but until such time as the garbage collector does so it will actually still be there (excluding any clever JVM optimisation of this simple example!).

    AFAIK there isn't an official definition of "dereferencing" in Java. Because there isn't the distinction between evaluation and assignment it does make sense, though it's not a term that I think is widely used.

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