logical structure/details of a reference variable and object in the memory?

后端 未结 4 780
感情败类
感情败类 2021-02-09 11:46

Let\'s say we have a class:

class Class1
{
   int i = 1;
}

and we have a variable:

Class1 ob1 = new Class1();
4条回答
  •  醉梦人生
    2021-02-09 12:01

    Every java object reference knows its class at runtime; this so-called "run-time type information" is used in code like this:

    if (obj instanceof class1) {
      // true!
    }
    

    You can also access the class of an object through obj.getClass(). This will return class1.class, an object of class Class. See the Object.getClass method.

    (Note that if your class is parameterized, as class1, the type of T will not be stored at runtime, due to "erasure".)

    I don't know whether the class information is stored with the pointer or with the data; it's probably implementation-specific in the jvm; but it hardly matters from a practical standpoint. (So either answer 1 or 2, or both, is "yes").

    The answer to 3 is that, as far as a java programmer is concerned, the run-time type information is encapsulated in an object of class Class. Under the covers, a JVM may implement this in one way or another.

提交回复
热议问题