What is a “runtime class” in Java?

后端 未结 4 1209
故里飘歌
故里飘歌 2021-01-12 11:51

I try to understand what the Object.getClass() method does.

The documentation says that it \"returns the runtime class of an object.\" That explanation

4条回答
  •  一个人的身影
    2021-01-12 12:38

    It means "the class of the instance the variable refers to at runtime" (sorry if that's not actually clearer).

    If you have a reference to an Object, it could refer to an Object, a String, an Integer... you get that class, not Object.

    Object obj1 = new Object();
    System.out.println(obj1.getClass());  // java.lang.Object
    
    String obj2 = "";
    System.out.println(obj2.getClass());  // java.lang.String
    
    obj1 = obj2;
    System.out.println(obj1.getClass());  // java.lang.String, not Object.
    

提交回复
热议问题