19

I was studying Polymorphism from "Head First Java" and came to this concept. Can anyone explain it please with an example?

Compiler checks the class of reference type -- not the Object type.

So what's the difference between Reference Type and Object Type?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Sikander
  • 2,799
  • 12
  • 48
  • 100

2 Answers2

47

I don't think their use of "object type" and "reference type" is standardized, but here's my interpretation.

Consider this code:

Object o = new Integer(3);

The reference o is of type Object. The object that it references is of type Integer.

So the "reference type" would be Object and the "object type" would be Integer.

What makes this confusing is that there's the (standardized, official) term "reference type" that encapsulates types that can be referenced. In Java that includes all classes, enums, interfaces, arrays. It excludes only the primitive types (int, ...).

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • If not "object type" and "reference type", what would be the more correct way for describing the two types in this polymorphic declaration? I have to say I've heard the use of object type and reference type used to describe polymorphism in both Java and Swift, would be curious what a more official terminology would be. – Adam Oct 02 '20 at 17:15
  • 1
    I'd just call them "the type of the reference" and "the type of the object". Yes, that can obviously be shortened to "reference type" and "object type" respectively, but I'd avoid those specific shortenings due to the kind of clash with existing definitions. – Joachim Sauer Oct 02 '20 at 21:48
  • 1
    Another way of describing a polymorphic declaration would be the "declared" type and the "real" type. In the example above, o's declared type would be Object, and o's real type would be Integer. – Adam Oct 14 '20 at 23:50
  • @Adam: I think "real" is misleading, because the type of the variable is no less real than the type of the object. – Joachim Sauer Oct 15 '20 at 10:05
11

What is meant by the terms is the following:

  • object type (in your book) = the actual runtime type of the referent
  • reference type (in your book) = the static type of the reference

Maybe some will find it easier to understand with these terms.

Bruno Reis
  • 37,201
  • 11
  • 119
  • 156